javascript - 在 Vue 中使用 Jest Mock 测试导出的模块
问题描述
我正在尝试对导出的模块进行模拟,但我不知道如何。以下是我的代码。
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
解决方案
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 实例的数据。
推荐阅读
- go - 从原始字节创建数据包并使用 gopacket 写入 pcap 文件
- javascript - 从 JavaScript 打开终端并运行 bash 命令 Linux
- c# - 无法在下拉列表中选择要选择的 SelectList 项
- git - 以前的 git bisect “会话”的状态是否存储在 git 的某个地方?
- python - Python Cerberus - 如果另一个不存在则需要一个
- latex - 如何将命令 zhnumber 替换为在 Latex 中添加英文数字的等效命令
- ethernet - 2 台设备如何通过以太网交换机进行通信
- javascript - 元素/值的每个更改列表上的 JavaScript 计数器为零(从零开始)
- flutter - 在颤动的输入字段上键入时如何更改文本字段
- ios - 如何将与现实世界对象的碰撞应用到 RealityKit 中的 3D 对象 (.usdz)?