我有一个导出几个类的 Node 模块,其中一个是 Client
,我用它来创建一个客户端(有一些 API 作为方法)。
我正在尝试使用 Jest 测试我的模块,该模块将此 Node 模块用作依赖项。但是,我无法成功模拟 Client 类中的一种方法(例如 search()
)。
这是我对 myModule
的规范:
//index.spec.ts
import * as nock from 'nock';
import * as externalModule from 'node-module-name';
import { createClient } from './../../src/myModule';
describe(() => {
beforeAll(() => {
nock.disableNetConnect();
});
it('test search method in my module', () => {
jest.mock('node-module-name');
const mockedClient = <jest.Mock<externalModule.Client>>externalModule.Client;
const myClient = createClient({/*params*/}); //returns instance of Client class present in node module by executing Client() constructor
myClient.searchByName('abc'); //calls search API - I need to track calls to this API
expect(mockedClient).toHaveBeenCalled();
expect(mockedClient.prototype.search).toHaveBeenCalledWith('abc');
});
});
但是,这根本不会创建模拟并触发 nock 错误,因为搜索 API 会尝试连接到 url(通过参数给出)。
我也尝试过像下面这样模拟 Client 类。虽然成功地为客户端类和搜索 API 创建了一个模拟(验证
search()
也通过控制台日志模拟),但当我尝试检查 search()
时它给了我一个错误。已被调用。externalModule.Client = jest.fn(() => { return { search: jest.fn(() => Promise.resolve('some response')) } });
//creates the mock successfully, but not sure how to track calls to 'search' property
const client = myModule.createClient(/*params*/);
client.searchByName('abc');
expect(externalModule.Client).toHaveBeenCalled(); //Successful
expect(externalModule.Client.prototype.search).toHaveBeenCalled(); //returns error saying "jest.fn() value must be a mock function or spy, Received: undefined"
我不确定我做错了什么。先感谢您。
最佳答案
模拟整个模块
尝试移动jest.mock
到文件顶部
//index.spec.ts
const search = jest.fn();
jest.mock('node-module-name', () => ({
Client: jest.fn(() => ({ search }))
}));
import * as nock from 'nock';
import * as externalModule from 'node-module-name';
import { createClient } from './../../src/myModule';
describe(() => {
beforeAll(() => {
nock.disableNetConnect();
});
it('test search method in my module', () => {
const myClient = createClient({/*params*/});
myClient.searchByName('abc');
expect(externalModule.Client).toHaveBeenCalled();
expect(search).toHaveBeenCalledWith('abc');
externalModule.Client.mockClear();
search.mockClear();
});
});
仅模拟客户端
创建
search
恒定并跟踪它。const search = jest.fn();
externalModule.Client = jest.fn(() => ({ search }));
const client = myModule.createClient(/*params*/);
client.searchByName('abc');
expect(externalModule.Client).toHaveBeenCalled();
expect(search).toHaveBeenCalled();
关于javascript - Jest - 在 typescript 中模拟一个命名的类导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55110711/