gpt4 book ai didi

nuxt.js - 使用 vitest 测试 Nuxt3 中的 Pinia 存储,抛出 `useRuntimeConfig` 未定义

转载 作者:行者123 更新时间:2023-12-05 08:45:38 41 4
gpt4 key购买 nike

我正在 nuxt3 应用程序中测试 pinia 商店。

在商店的 setup() 中,我正在使用 useRuntimeConfig 从公共(public)配置变量中获取计数器的初始值,我得到了这个错误 ReferenceError: useRuntimeConfig is没有定义不知道怎么解决

// store/counter.ts

...
state: () => {
const runtimeConfig = useRuntimeConfig()
const count = runtimeConfig.public.count
return {
...
count
...
}
},
...

代码

// store/counter.test.ts

import { fileURLToPath } from 'node:url'
import { describe, expect, it, beforeEach } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import { useCounter } from './counter'
import { setup } from '@nuxt/test-utils'

await setup({
rootDir: fileURLToPath(new URL('../', import.meta.url)),
server: true,
browser: true,
})

describe('Counter Store', () => {
beforeEach(() => {
// creates a fresh pinia and make it active so it's automatically picked
// up by any useStore() call without having to pass it to it:
// `useStore(pinia)`
setActivePinia(createPinia())
})

it('increments', () => {
const counter = useCounter()
expect(counter.n).toBe(0)
counter.increment()
expect(counter.n).toBe(1)
})

it('increments by amount', () => {
const counter = useCounter()
counter.increment(10)
expect(counter.n).toBe(10)
})
})

最佳答案

这看起来与我今天刚刚解决的问题类似。希望对您也有帮助:

  1. 在您的组件中,在本例中为 Pinia 存储模块,添加 useRuntimeConfig 的显式导入,如下所示:

    从“#imports”导入 {useRuntimeConfig}

目前,除了手动导入包之外,我没有更好的方法来解决“未定义”包的问题。随着 Nuxt3 的进步,我希望看到测试成为更多的焦点。 文档似乎建议从“#app”导入它,但我无法让它以这种方式工作,“#imports”似乎是更合适的别名。

  1. 在您的 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')
}
}
})
  1. 在您的测试文件中,使用 vi.mock() 函数模拟 #imports 包。
 vi.mock('#imports', () => {
return {
useRuntimeConfig() {
return {
public: {
// Your public config!
}
}
}
}
})

这让我可以在测试级别模拟 runtimeConfig - 希望它也能帮到你!祝你好运:D

对于阅读本文并希望在 Jest 中实现类似目标的任何人,this is the GitHub discussion这帮助我找到了这个解决方案。 不幸的是,我用来创建这个解决方案的讨论已经不存在了。 (404)

编辑:如果您需要在逐个测试的基础上更改模拟返回值,您可以返回在别处定义的对象并在您的测试中更改该对象的值。

    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()
}
}

关于nuxt.js - 使用 vitest 测试 Nuxt3 中的 Pinia 存储,抛出 `useRuntimeConfig` 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72192874/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com