Можно ли шпионить (шутить) несколько методов в одном модуле? - PullRequest
1 голос
/ 20 апреля 2020

Мне нужно шпионить за более чем одним методом в машинописи. Как добиться этого в машинописи?

// classA.ts
export class ClassA {
  public methodA() {
    this.methodB();
    this.methodC();
    return "ClassA";
  }
  public methodB() {}
  public methodC() {}
}

// classATest.ts
import {ClassA} from './classA';

it('Sample Test', async () => {
  const spyOn1 = jest.spyOn(ClassA, 'methodB');
    spyOn1.mockImplementation(() => {return () => {}});
    const spyOn2 = jest.spyOn(ClassA, 'methodC');
    spyOn2.mockImplementation(() => {return () => {}});

    const classA = new ClassA();
    expect(classA.methodA()).toEqual('ClassA');
});

Я получаю сообщение об ошибке - Argument of type '"methodC"' is not assignable to parameter of type '"methodB" | "prototype"'.

Разве мы не можем использовать несколько методов spyOn в классе? Есть ли другой способ добиться этого?

1 Ответ

2 голосов
/ 20 апреля 2020

Вам необходимо шпионить за methodB и methodC за ClassA.prototype. Это экземпляры методов, NOT class stati c методы.

Например, ClassA.ts:

export class ClassA {
  public methodA() {
    this.methodB();
    this.methodC();
    return 'ClassA';
  }
  public methodB() {}
  public methodC() {}
}

ClassA.test.ts:

import { ClassA } from './classA';

describe('61315546', () => {
  it('Sample Test', async () => {
    const spyOn1 = jest.spyOn(ClassA.prototype, 'methodB');
    spyOn1.mockImplementation(() => {
      return () => {};
    });
    const spyOn2 = jest.spyOn(ClassA.prototype, 'methodC');
    spyOn2.mockImplementation(() => {
      return () => {};
    });

    const classA = new ClassA();
    expect(classA.methodA()).toEqual('ClassA');
  });
});

Результаты модульных испытаний с отчетом о покрытии:

 PASS  stackoverflow/61315546/ClassA.test.ts (12.1s)
  61315546
    ✓ Sample Test (3ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |      50 |     100 |                   
 ClassA.ts |     100 |      100 |      50 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.974s
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...