Синон макет класс - PullRequest
       6

Синон макет класс

0 голосов
/ 10 февраля 2020

У меня есть класс:

export default class A {
  data: string
  constructor(data?: any) {
    if (data !== undefined) {
      this.data = data.stingValue
    }
  }
}

Затем у меня есть другой класс, который использует A конструктор внутри publi c метод:

export default class B {
  public doSomething(data: any) {
    const a = new A(data)
    dependecy.doAnotherThing(a)
  }
}

И тест:

it(('shoud doSomething') => {
  const doAnotherThingStub = stub(B.prototype, 'doAnotherThing')
  //this part does not work, just an example of what I would like to achieve
  const doAnotherThingStub = stub(A.prototype, 'constructor').returns({dataReturendFromAConstructorStub: true})
  // end of this part
  const b = new B()
  b.doSomething({})
  expect(doAnotherThingStub.calledWith({dataReturendFromAConstructorStub: true})).to.be.true
})

И моя цель - заглушить конструктор класса А. У меня есть отдельные тесты для класса А, и я не хочу проверять это снова. Мне нужно что-то вроде stub(A.prototype,'constructor'). Я пытался использовать proxyquire и заглушки, но я не смог внедрить поддельный конструктор, либо вызывается реальный конструктор, либо я получаю что-то вроде: A_1.default is not a constructor. Ранее у меня были случаи, когда мне нужно было заглушить класс, который я вызываю прямо в тестовом примере, или заглушить метод класса, и это довольно просто. Но я борюсь с этим делом.

Какой правильный способ насмешки над A?

1 Ответ

1 голос
/ 11 февраля 2020

Вот решение для модульного тестирования с использованием proxyquire и sinon:

a.ts:

export default class A {
  private data!: string;
  constructor(data?: any) {
    if (data !== undefined) {
      this.data = data.stingValue;
    }
  }
}

b.ts:

import A from './a';

export default class B {
  public doSomething(data: any) {
    const a = new A(data);
  }
}

b.test.ts:

import sinon from 'sinon';
import proxyquire from 'proxyquire';

describe('60152281', () => {
  it('should do something', () => {
    const aStub = sinon.stub();
    const B = proxyquire('./b', {
      './a': {
        default: aStub,
      },
    }).default;
    const b = new B();
    b.doSomething({});
    sinon.assert.calledWithExactly(aStub, {});
  });
});

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

  60152281
    ✓ should do something (1908ms)


  1 passing (2s)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   66.67 |        0 |      50 |   66.67 |                   
 a.ts     |   33.33 |        0 |       0 |   33.33 | 4,5               
 b.ts     |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
...