首页 > 解决方案 > 来自节点模块的 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()部分,但我不知道为什么!

标签: javascriptnode.jsmockingjestjs

解决方案


您缺少模拟构造函数。

这模拟了的构造函数restclient

jest.mock('restclient', ()=> jest.fn().mockImplementation(() => {

 /** here you can create and return a mock of request **/

}));

推荐阅读