Тестовая цепочка функций с Jest - PullRequest
1 голос
/ 25 марта 2020

Это пример моего класса:

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

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

Используя Jest, как я могу утверждать, что «secondMethod» будет вызываться при вызове «myMainMethod». MyLib - сторонняя библиотека.

1 Ответ

1 голос
/ 25 марта 2020

Вот решение для модульного теста:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...