Open dw08 opened 3 years ago
@dw08
这样会断言失败,请问该怎么处理呢
原因:shallowMount
的时候,mounted()函数就已经执行结束了。后面再mock的话,毫无意义。
测试方法:
const mockCheckLoginState=jest.fn();
const wrapper = shallowMount(Home,{ metheds: { checkLoginState : mockCheckLoginState }});
expect(mockCheckLoginState).toHaveBeenCalled();
需要注意的是,如果@vue/test-utils和vue-jest是最新版本的话,有可能上面的测试也会失败,可以利用vue的mixins
const mockCheckLoginState=jest.fn();
const LocalMixins = {
methods: {
checkLoginState: mockCheckLoginState,
},
};
const wrapper = shallowMount(Home,{ mixins: [LocalMixins] });
expect(mockCheckLoginState).toHaveBeenCalled();
组件
mounted () { this.checkLoginState(); }, methods: { checkLoginState () { if (this.hasLogin) { this.$router.push("/goods") return; } } }
测试代码const wrapper = shallowMount(Home) const checkLoginStateStub = jest.spyOn(wrapper.vm, "checkLoginState"); expect(checkLoginStateStub).toHaveBeenCalled();
这样会断言失败,请问该怎么处理呢