I. *_*ota 6 javascript typescript vue.js jestjs vuex
我有一个基于 TypeScript 的 Vue 项目,使用Jest作为测试框架。我在要测试的模块中有操作。
我的操作如下所示:
@Action({})
saveSomeData (payload: any): Promise<any> {
const { isActive, id, routes } = payload
return this.context.dispatch('otherModule/createId', '', { root: true })
.then((id: string) => {
payload = { isActive, id, routes, type: 'postRoutes' }
return this.context.dispatch('submitRoutes', payload)
})
}
@Action({})
submitRoutes (payload: any): Promise<any> {
const { isActive, id, routes, type } = payload
return ActiveService.setActive(id)
.then(() => this.context.dispatch(type, { id, routes }))
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试的样子:
// Mocking createId in otherModule module to return ID
jest.mock('@/store/modules/otherModule', () => ({
createId: jest.fn(() => Promise.resolve([
{
id: 'someId'
}
]))
}))
...
describe('Testing save MyModule data', () => {
let store: any
beforeEach(() => {
store = new Vuex.Store({
modules: {
myModule,
otherModule
}
})
})
test('Should call createId and then call submitRoutes if ID is empty', async () => {
const payload = {
isActive: true,
id: '',
routes: []
}
const pld = {
isActive: true,
id: 'someId',
routes: [],
type: 'postRoutes'
}
store.dispatch = jest.fn()
await store.dispatch('myModule/saveSomeData', payload)
expect(store.dispatch).toHaveBeenCalledWith('myModule/saveSomeData', payload)
expect(store.dispatch).toHaveBeenCalledWith('otherModule/createId') // <-- here I get an error
expect(store.dispatch).toHaveBeenCalledWith('myModule/submitRoutes', pld)
})
})
Run Code Online (Sandbox Code Playgroud)
问题:我的测试失败了,我还没有找到任何让它工作的方法。
错误:
Error: expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: "otherModule/createId"
Received: "myModule/saveSomeData", {"id": "", "isActive": true, "routes": []}
Number of calls: 1
Run Code Online (Sandbox Code Playgroud)
我试过的
我已经遵循Vuex文档和Jest,我还尝试了来自互联网的不同解决方案 - 不幸的是没有运气。
我将不胜感激任何帮助。
store.dispatch = jest.fn()使调度函数成为无操作,它不会调用saveSomeData,因此不会调度其他操作。
这个断言没有用,因为它基本上测试了上一行:
expect(store.dispatch).toHaveBeenCalledWith('myModule/saveSomeData', payload)
Run Code Online (Sandbox Code Playgroud)
store.dispatch间谍或存根不应该影响context.dispatch操作,因为上下文是在存储初始化时创建的并且已经使用原始的dispatch。可能没有必要这样做,因为这些是应该测试的操作,而不是 Vuex 本身。
jest.mock可以使用和在模块级别监视操作jest.requireActual,或者如果需要,可以在 Vuex 模块对象上本地监视操作。模块间谍和模拟应该发生在顶层。对象间谍和模拟应该在存储实例化之前发生。
在这种情况下,测试的单元是myModule动作,ActiveService.setActive可以otherModule/createId被视为不同的单元并且应该被模拟。如果postRoutes包含副作用,它们也可以被嘲笑。
jest.spyOn(otherModule.actions, 'createId');
jest.spyOn(ActiveService, 'setActive');
store = new Vuex.Store(...)
...
otherModule.actions.createId.mockValue(Promise.resolve('stubbedId'));
ActiveService.setActive.mockValue(Promise.resolve());
await store.dispatch('myModule/saveSomeData', payload)
// assert otherModule.actions.createId call
// assert ActiveService.setActive call
// assert otherModule.actions.postRoutes call
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
894 次 |
| 最近记录: |