繁体   English   中英

来自节点模块的 JEST Mocking

[英]JEST Mocking from node modules

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

我尝试了很多解决方案(__ 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 **/

}));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM