【问题标题】:Test exported module with Jest Mock in Vue在 Vue 中使用 Jest Mock 测试导出的模块
【发布时间】:2019-04-10 09:01:03
【问题描述】:

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

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 这样默认导出的模块。

【问题讨论】:

标签: javascript unit-testing vue.js jestjs


【解决方案1】:

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

这样我就可以处理mock函数,查看变化的ui元素或者vue实例的数据了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-30
    • 2018-09-16
    • 2017-07-15
    • 2021-08-02
    • 1970-01-01
    • 2021-10-11
    • 2020-05-21
    • 2020-06-02
    相关资源
    最近更新 更多