在Vue中使用Jest Mock测试导出的模块

时间:2019-04-10 09:01:03

标签: javascript unit-testing vue.js jestjs

我正在尝试在导出的模块上进行模拟,但是我不知道如何做。以下是我的代码。

api

// @/src/api/index.js

...
export const foo = {
  fetch() {
    return Promise.resolve()
  }
}

vue

import { foo } from '@/api' 

...
data() {
  return {
    receivedData: ''
  }
},
methods: {
  onClickButton() {
    // event listener
    foo.then(data => { this.receivedData = data }
  }
}

test.spec.js

import { shallowMount } from '@vue/test-utils'
import { foo } from '@/api'
...
jest.mock('../../../src/api/index.js') // it does not mock foo

...
  beforeEach(() => {
    foo.mockClear()
    // error : _api.foo.mockClear is not a function
  })

在此示例中,我如何模拟以名称导出foo,而不是像exported default foo那样默认导出的模块。

1 个答案:

答案 0 :(得分:0)

api

// @/src/api/index.js

...
export const foo = {
  fetch() {
    return Promise.resolve()
  }
}

// add following
export default {
  foo
}

test.spec.js

import { shallowMount } from '@vue/test-utils'
import api from '@/api' // get a object which have all api functions
...
jest.mock('../../../src/api/index.js', () => {
  // make it similar with 'export default' of api/index.js
  return {
    foo: {
      fetch: jest.fn(() => {
        return {
          then(callback) {
            // pass dummy data as you want or need
            callback({ data: { success: true } })
          }
        }
      })
    }
  }
})

...
  beforeEach(() => {
    // clear mock of each mocked function
    api.foo.fetch.mockClear()
  })

  it('test api', () => {
    const wrapper = shallowMount(Component)
    wrapper.find('button').trigger('click')

    expect(api.foo.fetch).toHaveBeenCalled() // pass it
  })

  it('test api2', () => {
    expect(api.foo.fetch).toHaveBeenCalled() // do not pass it
  })

通过这种方式,我可以处理模拟功能并检查已更改的ui元素或vue实例的数据。