2

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

const accessValue = await objValueClass.getValue();

在运行 component.test.js 时,inconsole.log accessValue即将到来undefined

组件.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();
  });
});

组件.js

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

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

module.exports = component;

值类.js

class ValueClass {

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

}

module.exports = {
  ValueClass
};
4

1 回答 1

0

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

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
于 2020-12-02T03:26:31.123 回答