簡體   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