这看起来与我今天刚刚解决的问题相似。希望它也对您有帮助:
-
在您的组件中,在本例中为 Pinia 存储模块,添加 useRuntimeConfig 的显式导入,如下所示:
import { useRuntimeConfig } from '#imports'
目前,除了手动导入包之外,我没有更好的方法来解决包“未定义”的问题。随着 Nuxt3 的进展,我希望看到测试变得更加受关注。文档似乎建议从“#app”导入它,但我无法让它以这种方式工作,“#imports”似乎是更合适的别名。
- 在您的 vitest.config.js 中,添加映射的别名
#imports
打包到隐藏的 nuxt 文件。 vitest.config.js 文件的示例如下:
export default defineConfig({
test: {
// other test specific plugins
},
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, './'),
'~': path.resolve(__dirname, './'),
'#imports': path.resolve(__dirname, './.nuxt/imports.d.ts')
}
}
})
- 在您的测试文件中,使用 vi.mock() 函数来模拟
#imports
包裹。
vi.mock('#imports', () => {
return {
useRuntimeConfig() {
return {
public: {
// Your public config!
}
}
}
}
})
这使我能够在测试级别模拟 runtimeConfig - 希望它也对您有帮助!祝你好运:D
For anybody reading this wanting to achieve a similar thing in Jest, this is the GitHub discussion that helped me figure this solution out. Unfortunately the discussion I used to create this solution no longer exists. (404)
编辑:如果您需要在逐个测试的基础上更改模拟返回值,您可以返回在其他地方定义的对象并更改测试中该对象的值。
i.e.
let storeMock = {
user: {
getUsername: 'Jane Doe',
setUsername: vi.fn()
}
}
vi.mock('#imports', () => {
return {
useNuxtApp: vi.fn().mockImplementation(() => ({
$store: {
...storeMock
}
})),
}
})
// In your test
storeMock = {
user: {
getUsername: 'Janet Van Dyne',
setUsername: vi.fn()
}
}