用Jest测试功能链

时间:2020-03-24 23:22:03

标签: javascript jestjs

这是我班的一个例子:

class MyClass {
    constructor() {
        this.myLib = new MyLib()
    }

    myMainMethod = param => {
        this.myLib.firstMethod(arg => {
            arg.secondMethod(param)
        })
    }
}

使用Jest,我如何断言将通过调用“ myMainMethod”来调用“ secondMethod”。 MyLib是第三方库。

1 个答案:

答案 0 :(得分:1)

这是单元测试解决方案:

index.ts

import { MyLib } from './MyLib';

export class MyClass {
  myLib;
  constructor() {
    this.myLib = new MyLib();
  }

  myMainMethod = (param) => {
    this.myLib.firstMethod((arg) => {
      this.myLib.secondMethod(arg);
    });
  };
}

index.test.ts

import { MyClass } from './';
import { MyLib } from './MyLib';

describe('60840838', () => {
  it('should pass', () => {
    const firstMethodSpy = jest.spyOn(MyLib.prototype, 'firstMethod').mockImplementationOnce((callback) => {
      callback('arg');
    });
    const secondMethodSpy = jest.spyOn(MyLib.prototype, 'secondMethod').mockReturnValueOnce('fake');
    const instance = new MyClass();
    instance.myMainMethod('param');
    expect(firstMethodSpy).toBeCalledWith(expect.any(Function));
    expect(secondMethodSpy).toBeCalledWith('arg');
  });
});

具有覆盖率报告的单元测试结果:

 PASS  stackoverflow/60840838/index.test.ts
  60840838
    ✓ should pass (4ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |    87.5 |      100 |   71.43 |   85.71 |                   
 MyLib.ts |   71.43 |      100 |   33.33 |   66.67 | 3,6               
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.54s, estimated 8s