单元测试,检查函数是否被调用

Unit tests, check if function have been called

我需要执行一个测试来检查函数是否在按钮点击时被调用

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

我需要测试函数 createDimension。在我的测试中我嘲笑它

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

在项目中,函数是这样导出的

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

我希望这个测试能成功。但由于某些原因 wrapper.qiwaApi 或 wrapper.createDimension return undefined

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

包装器不会以这种方式提供对模拟的访问。

您必须保留对 jest.fn() 的引用,然后直接验证对该引用的调用,而不是尝试将其从包装器中拉出:

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