[Vuejs]-Testing inner logic of method using vue-test-utils with Jest

0👍

You have to extract this.isLoading rows into a new method setLoading() and check if it was called.

0👍

The second argument of shallowMount/mount is the mounting options that could be used to override the component’s data props upon mounting. This lets you pass in a setter that mocks the isLoading data prop, which then allows you to verify the property was modified within the method under test:

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


  //...
})

Then, you could use toHaveBeenCalledTimes() along with isLoadingSetter.mock.calls[] to examine the arguments of each call to the mocked setter. And since you want to test the effects of the async method, you’ll have to await the method call before making any assertions:

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

If you also want to verify that GET_OFFERS() is called, you could use jest.spyOn() on the component’s method before mounting:

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

Leave a comment