简体   繁体   中英

How do I stub a module with Jest and Proxyquire?

I want to force node-fetch to be a stub and I'm having a bit of trouble getting it to work. Code:

const fetchMock = jest.fn();

const {
  getArticle 
} = require('../../sfpublish/api');
console.log('loaded api')
const A = global.proxyquire('../../sfpublish/api', {
  'node-fetch': fetchMock
});

setup.js :

global.proxyquire = require('proxyquire');

package.json :

"jest": {
    "automock": false,
    "globalSetup": "./test/__config.js",
    "setupFiles": [
      "./test/__setup.js"
    ]
  },

Result:

FAIL  test/sfpublish/api.test.js
  ● Test suite failed to run

    Cannot find module '../../sfpublish/api'

      23 | } = require('../../sfpublish/api');
      24 | console.log('loaded api')
    > 25 | const A = global.proxyquire('../../sfpublish/api', {
         |                  ^
      26 |   'node-fetch': fetchMock
      27 | });

How can it be failing to load the module that I just loaded 2 lines previous? Is proxyquire not the right module to use here?

I've gotten node-fetch to be a mock in my test but when I run the function in the module (which has const fetch = require('node-fetch'); at the top) it's going to the real module instead of the fake. I've tried using fetch mocking libs like fetch-mock to no avail.

I ended up putting a mock in:

test/__mocks__/node-fetch.js

'use strict';
const nodeFetch = jest.genMockFromModule('node-fetch');
module.exports = nodeFetch;

package.json:

 "jest": {
    "verbose": true,
    "automock": false,
    "globalSetup": "./test/__config.js",
    "coverageReporters": [
      "text-summary",
      "html"
    ],
    "roots": [
      "./test"
    ],
    "setupFiles": [
      "./test/__setup.js"
    ]
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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