首页 > 解决方案 > VanillaJS 每个测试模拟

问题描述

我正在编写一些代码,我有一个我想要实现的虚拟场景,如下所示。我有一个正在测试的函数,它使用来自不同模块的函数。我想模拟导入模块的功能。我该怎么做呢?

我见过这个解决方案,但该jest.doMock功能在 commonJS 中不起作用 - 这是我所理解的。这是一个节点后端项目。

任何帮助,将不胜感激。谢谢

// helper.js

let add = (a, b) => a + b;
let mult = (a, b) => a * b;

module.exports = { add, sub, mult };
// index.js

const { add, mult } = require('./helper');

const add5thenMultiply2 = (a) => {
  const res1 = add(a, 5);
  return mult(res1, 2);
};

module.exports = { add5thenMultiply2 };
// index.test.js

const { add5thenMultiply2 } = require('./index');

describe('index', () => {
  it('returns right value', () => {
    const input = 3;
    const expected = 16;
    const result = add5thenMultiply2(input);
    expect(result).toEqual(expected);
  });

  it('works with mock', () => {
    // mock add() such that it always returns 100, but for this test only
    const input = 3;
    const expected = 200;
    const result = add5thenMultiply2(input);
    expect(result).toEqual(expected);
  });
});

标签: javascriptunit-testingtestingjestjsmocking

解决方案


jest.doMock(moduleName, factory, options)适用于 commonJS。您还需要使用jest.requireActual(moduleName)部分模拟./helper模块,这意味着仅模拟add功能,继续使用原始mult功能。

例如

helper.js

let add = (a, b) => a + b;
let mult = (a, b) => a * b;

module.exports = { add, mult };

index.js

const { add, mult } = require('./helper');

const add5thenMultiply2 = (a) => {
  const res1 = add(a, 5);
  return mult(res1, 2);
};

module.exports = { add5thenMultiply2 };

index.test.js

describe('index', () => {
  beforeEach(() => {
    jest.resetModules();
  });
  it('returns right value', () => {
    const { add5thenMultiply2 } = require('./index');
    const input = 3;
    const expected = 16;
    const result = add5thenMultiply2(input);
    expect(result).toEqual(expected);
  });

  it('works with mock', () => {
    jest.doMock('./helper', () => {
      return {
        ...jest.requireActual('./helper'),
        add: jest.fn().mockReturnValue(100),
      };
    });
    const { add5thenMultiply2 } = require('./index');
    const input = 3;
    const expected = 200;
    const result = add5thenMultiply2(input);
    expect(result).toEqual(expected);
  });
});

测试结果:

 PASS  examples/67830139/index.test.js (7.751 s)
  index
    ✓ returns right value (6554 ms)
    ✓ works with mock (2 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 helper.js |     100 |      100 |     100 |     100 |                   
 index.js  |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        8.308 s

推荐阅读