holylovelqq / vue-unit-test-with-jest

吃透本仓库,变身vue项目单体测试大神
487 stars 90 forks source link

断言vue生命周期中是否触发某个函数该怎么处理 #31

Open dw08 opened 3 years ago

dw08 commented 3 years ago

组件 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(); 这样会断言失败,请问该怎么处理呢

holylovelqq commented 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();