Search code examples
vue.jsunit-testingvue-test-utils

Unit tests, check if function have been called


I need to implement a test that checks if the function has been called on the button click

onSave (e) {
 this.$qiwaApi.createDimension()
   .then(() => {})
   .catch(err => this.showSnackbar(err.message))}

I need to test the function createDimension. In my test i mocked it

const createComponent = () => {
    wrapper = mount(dimensions, {
      store,
      localVue,
      mocks: {
        $qiwaApi: {
          createDimension: function (e) {
            return new Promise((resolve) => { resolve({}) })
          }
        }
      },
      router
    })
  }

In the project, the function exported this way

export default $axios => ({
  createDimension (data, surveyId) {
    return $axios.post(`/lmi-admin/surveys/${surveyId}/dimension`, {
      data: {
        attributes: {
          ...data
        }
      }
    })
  }
})

I expect this test to work. But for some reason wrapper.qiwaApi or wrapper.createDimension return undefined

expect(wrapper.$qiwaApi.createDimension).toHaveBeenCalled()

Solution

  • The wrapper doesn't provide access to your mocks that way.

    You would have to hold a reference to a jest.fn(), and then verify the calls on that reference directly instead of trying to pull it out of the wrapper:

    it('calls createDimension on button click', async () => {
      const createDimension = jest.fn(() => Promise.resolve())
      const wrapper = mount(dimensions, {
        mocks: {
          $qiwaApi: {
            createDimension
          }
        }
      })
    
      await wrapper.find('[data-testid="save"]').trigger('click')
      expect(createDimension).toHaveBeenCalled()
    })
    

    demo