使用带有Jest的vue-test-utils测试方法的内部逻辑

问题描述

如何测试以下方法的内部逻辑?

例如:

async method () {
  this.isLoading = true;
  await this.GET_OFFERS();
  this.isLoading = false;

  this.router.push("/somewhere");
}

因此,我有一种方法可以切换isLoading调用操作并路由到某个地方。我如何确定isLoading的切换正确(操作调用之前为true,之后调用为false)?

解决方法

您必须将this.isLoading行提取到新方法setLoading()中,并检查是否被调用。

,

shallowMount / mount的第二个参数是mounting options,在挂载时可以用来覆盖组件的数据属性。这样,您就可以传入一个模拟isLoading数据道具的setter,然后可以验证该属性是否在被测方法中被修改了:

it('sets isLoading',() => {
  const isLoadingSetter = jest.fn()

  const wrapper = shallowMount(MyComponent,{
    data() {
      return {
        // This setter is called for `this.isLoading = value` in the component.
        set isLoading(value) {
          isLoadingSetter(value)
        }
      }
    }
  })


  //...
})

然后,您可以将toHaveBeenCalledTimes()isLoadingSetter.mock.calls[]一起使用来检查对模拟的setter的每次调用的参数。而且,由于您想测试async方法的效果,因此必须在进行任何断言之前await进行方法调用:

it('sets isLoading',async () => {
  //...

  await wrapper.vm.method()

  expect(isLoadingSetter).toHaveBeenCalledTimes(2)
  expect(isLoadingSetter.mock.calls.[0][0]).toBe(true)
  expect(isLoadingSetter.mock.calls.[1][0]).toBe(false)
})

如果您还想验证是否调用了GET_OFFERS(),则可以在安装 之前在组件的方法上使用jest.spyOn()

it('gets offers',async () => {
  const getOfferSpy = jest.spyOn(MyComponent.methods,'GET_OFFERS')
  const wrapper = shallowMount(MyComponent,/*...*/)
  await wrapper.vm.method()
  expect(getOfferSpy).toHaveBeenCalledTimes(1)
})