从节点模块嘲笑

时间:2020-04-24 16:50:53

标签: javascript node.js mocking jestjs

我已经尝试了一段时间,但找不到解决方法。

我尝试了很多解决方案(__模拟__文件夹,mockimplementation,mock等),但我始终遇到相同的错误 client.mockImplementation不是函数 < / p>

//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()部分,但我不知道为什么!

1 个答案:

答案 0 :(得分:2)

您想模拟构造函数。

这嘲笑jest.mock('restclient', ()=> jest.fn().mockImplementation(() => { /** here you can create and return a mock of request **/ })); 的构造函数

{{1}}