【问题标题】:unable to mock the instance function of class (function from new instance of class) in nodejs using jest无法使用 jest 在nodejs中模拟类的实例函数(来自类的新实例的函数)
【发布时间】:2021-03-13 18:52:00
【问题描述】:

在component.js中,需要mock一行:

const accessValue = await objValueClass.getValue();

在运行 component.test.js 时,console.log accessValueundefined 的形式出现

component.test.js

describe('** Handler unit tests **', () => {
  test('test 1', async () => {
    const { ValueClass } = require('../../ValueClass');
    jest.mock('../../ValueClass');
    const objValueClass = new ValueClass();
    objValueClass.getValue.mockResolvedValue('abcd');
    const { component } = require('../../component');
    const res = await component();
  });
});

component.js

const { ValueClass } = require('../../ValueClass');
 
const component = async () => {

        const objValueClass = new ValueClass();
        const accessValue = await objValueClass.getValue();
        console.log('accessValue###', accessValue);
}

module.exports = component;

ValueClass.js

class ValueClass {

      async getValue() {
        const a = 'a';
        const b = 'b';
        return a+b;
      }

}

module.exports = {
  ValueClass
};

【问题讨论】:

  • 测试中的 objValueClass 与组件中的实例不同。应该是ValueClass.prototype.getValue.mockResolvedValue(...)
  • 工作@EstusFlask。谢谢

标签: node.js jestjs mocking jest-mock-axios


【解决方案1】:

这是我的单元测试解决方案:

component.test.js:

const { ValueClass } = require('./ValueClass');
const component = require('./component');

jest.mock('./ValueClass', () => {
  const valueClassInstance = {
    getValue: jest.fn(),
  };
  return { ValueClass: jest.fn(() => valueClassInstance) };
});

describe('** Handler unit tests **', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  test('test 1', async () => {
    const objValueClass = new ValueClass();
    objValueClass.getValue.mockResolvedValue('abcd');
    const res = await component();
    expect(objValueClass.getValue).toBeCalledTimes(1);
  });
});

单元测试结果:

 PASS  src/stackoverflow/65097473/component.test.js (9.297s)
  ** Handler unit tests **
    ✓ test 1 (16ms)

  console.log src/stackoverflow/65097473/component.js:764
    accessValue### abcd

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

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 2020-07-13
    • 2018-01-16
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多