【问题标题】:How do I stub a module with Jest and Proxyquire?如何使用 Jest 和 Proxyquire 存根模块?
【发布时间】:2018-12-15 13:21:24
【问题描述】:

我想强制 node-fetch 成为存根,但我遇到了一些麻烦 让它工作。代码:

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"
    ]
  },

结果:

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 | });

怎么会无法加载我之前加载 2 行的模块? proxyquire 不是在这里使用的正确模块吗?

我已经让node-fetch 在我的测试中成为一个模拟,但是当我在模块(顶部有const fetch = require('node-fetch');)中运行该函数时,它会进入真正的模块而不是假模块。我试过使用像fetch-mock 这样的获取模拟库但无济于事。

【问题讨论】:

标签: mocking jestjs proxyquire node-fetch


【解决方案1】:

我最后放了一个模拟:

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"
    ]
  }

【讨论】:

    猜你喜欢
    • 2015-07-08
    • 2021-01-21
    • 2018-08-12
    • 2018-08-07
    • 2018-05-05
    • 2021-02-16
    • 2021-09-23
    • 2017-06-10
    相关资源
    最近更新 更多