javascript - 来自节点模块的 JEST 模拟
问题描述
我已经尝试了一段时间,但找不到解决方案。
我尝试了很多解决方案(__ mock __ 文件夹、mockimplementation、mock 等等),但我总是遇到同样的错误client.mockImplementation is not a function
//restclient.js
module.exports = (cfg) => new Client(config);
// api.js
const client = require('restclient');
module.exports.doRequest = () => {
const request = client();
const config = {};
request.get('/path/to/request', config)
.then(result => console.log(result))
}
//api.tests.js
const client = require('restclient');
const api = require('./api');
jest.mock('restclient', () => () => ({
get: jest.fn(),
}));
describe('testing API', () => {
test('test then', async () => {
try {
restclient.mockImplementation(() => () => ({
get: (url, config) => 'Hi! I\'m mocked',
}));
const result = await api.doRequest();
console.log('result', result);
} catch (e) {
console.log('eee', e);
}
});
});
我找不到解决方案,我想我无法模拟该const request = restclient()
部分,但我不知道为什么!
解决方案
您缺少模拟构造函数。
这模拟了的构造函数restclient
jest.mock('restclient', ()=> jest.fn().mockImplementation(() => {
/** here you can create and return a mock of request **/
}));
推荐阅读
- css - TailwindCSS 电话断点溢出-x 问题
- xaml - Xamarin Forms:如何在选择/取消选择 FlyoutItem.Icon 时更改它的颜色?
- html - bootstrap.min.css.map 出现在奇怪的地方
- qt - QML 关于调用嵌套变量的问题
- unity3d - ScriptableObject,添加了一个字段,资产不更新,怎么办?
- python - 无法读取 npy 文件
- apache-spark - PySpark:在 Barplot 中使用 TransformedDStream
- r - 使用 for 循环重命名数据框中的变量
- julia - Pluto Notebook 中的变量输出
- c++ - 排序函数在 C++17 上返回错误的对象类型