javascript - 模拟模块中除一个函数之外的所有函数

标签 javascript node.js jestjs mocking

我正在测试 fileA.js,它需要 fileB.js

fileA.test.js 中,我希望模拟 fileB.js 中除一个之外的所有方法。

fileA.test.js中我有:

const common = require("../src/fileB");
jest.mock("../src/fileB");

有一种方法我不想被 mock 。这种事情在nodeJS中可能吗?

谢谢。

最佳答案

您可以使用jest.mockjest.requireActual(moduleName)部分模拟模块的方法/函数。

例如:

a.js:

const b = require('./b');

exports.main = function main() {
  console.log(b.method1());
  console.log(b.method2());
  console.log(b.method3());
};

b.js:

module.exports = {
  method1: function() {
    return 'method 1';
  },

  method2: function() {
    return 'method 2';
  },

  method3: function() {
    return 'method 3';
  }
};

现在,我们将模拟除 method3 之外的 b.js 的所有方法。

a.spec.js:

jest.mock('./b', () => {
  const originalB = jest.requireActual('./b');
  const partialMockedB = Object.keys(originalB).reduce((pre, methodName) => {
    pre[methodName] = jest.fn();
    return pre;
  }, {});
  return {
    ...partialMockedB,
    method3: originalB.method3 // mock all methods of b except method3
  };
});

const { main } = require('./a');
const b = require('./b');

describe('main', () => {
  test('should correct', () => {
    const logSpy = jest.spyOn(console, 'log');
    b.method1.mockReturnValueOnce('mocked method 1');
    b.method2.mockReturnValueOnce('mocked method 2');
    main();
    expect(logSpy.mock.calls[0]).toEqual(['mocked method 1']);
    expect(logSpy.mock.calls[1]).toEqual(['mocked method 2']);
    expect(logSpy.mock.calls[2]).toEqual(['method 3']);
  });
});

单元测试结果:

 PASS  src/stackoverflow/58561765/a.spec.js
  main
    ✓ should correct (18ms)

  console.log node_modules/jest-mock/build/index.js:860
    mocked method 1

  console.log node_modules/jest-mock/build/index.js:860
    mocked method 2

  console.log node_modules/jest-mock/build/index.js:860
    method 3

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.65s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58561765

关于javascript - 模拟模块中除一个函数之外的所有函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58561765/

相关文章:

javascript - 在javascript中读取文件并显示内容

javascript - 将 2 列与容器对齐

node.js - 在 azure 上部署 Node 应用程序时出现意外 token )?

node.js - 使用 Node 请求管道图像,但在非 200 http 状态代码时中止

node.js - Sequelize 模型 - 在 Node 中同步时设置关联

jestjs - Jest 断言 - 包含 key 的对象

javascript - 显示和隐藏并不相反

php - 如何解析 API 调用中的 JSON 数据?

node.js - 在 ElectronJS 中使用 Electron-Remote 开 Jest 测试 React 组件

javascript - Jest 遇到意外 token : SyntaxError: Unexpected Token {