从节点模块进行JEST嘲讽

问题描述 投票:0回答:1

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

我尝试了很多解决方案(__ mock __文件夹,mockimplementation,mock等等),但我总是遇到同样的错误。client.mockImplementation不是一个函数。

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

javascript node.js mocking jestjs
1个回答
2
投票

你缺少对构造函数的模拟。

这将模拟 restclient

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

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

}));
© www.soinside.com 2019 - 2024. All rights reserved.