gpt4 book ai didi

javascript - 如何用 Jest 模拟实例化对象

转载 作者:行者123 更新时间:2023-11-28 20:35:32 25 4
gpt4 key购买 nike

我有一个执行此操作的文件 (src/dclient):

import DataClient from 'src/clients/data'

const DClient = new DataClient({ id: 'xxx' })
export default DClient

我有一个文件(我正在尝试测试)执行此操作:

import DClient from src/dclient

// Some code

DClient.alert('hello')

我正在尝试在 Dclient.alert 上写期望,但没有成功。我试图将 Jest 测试设置为:

alertMock = jest.fn();
require('src/dclient').alert = alertMock

但是当我检查 alertMock.mock.calls 时这不起作用,即使我知道它已被调用。我认为是因为 dclient 返回了一个实例,实际上并没有在其上定义警报。

我如何设置这个 Jest ,以便我可以写下警惕的期望?

最佳答案

有几种方法可以对此进行测试。

您尝试的方式工作正常,您只需要将其更改为:

test('code', () => {
const alertMock = jest.fn();
require('src/dclient').default.alert = alertMock; // <= mock alert on 'default'

require('./code'); // <= require the code that calls DClient.alert('hello')
expect(alertMock).toHaveBeenCalledWith('hello'); // Success!
})

...因为 src/dclient 是一个带有 default 导出的 ES6 模块。


我可能会使用的方法是在 DataClient 类上模拟 alert 函数:

import DataClient from 'src/clients/data';

test('code', () => {
const alertSpy = jest.spyOn(DataClient.prototype, 'alert');
alertSpy.mockImplementation(() => {});

require('./code'); // <= require the code that calls DClient.alert('hello')
expect(alertSpy).toHaveBeenCalledWith('hello'); // Success!
})

关于javascript - 如何用 Jest 模拟实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55337053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com