У меня есть React JS компонент MyComponent
, и я хотел бы протестировать следующий вариант использования:
Он должен вызывать updateSomething()
при установке компонента
И я придумал следующий код:
Тестируемая система (SUT)
export class MyComponent extends React.Component<Props, State> {
public componentDidMount() {
console.log("componentDidMount"); // Debug purpose.
this.fetchSomething()
.then(() => {
console.log("fetchSomething"); // Debug purpose.
this.updateSomething();
});
}
// These are public for simplicity
public async fetchSomething(): Promise<any> { }
public updateSomething() {
console.log("updateSomething"); // Debug purpose.
}
}
Тест
it("should update something, when on mount", () => {
const props = { ...baseProps };
sinon.stub(MyComponent.prototype, "fetchSomething").resolves();
const spy = sinon.spy(MyComponent.prototype, "updateSomething");
shallow(<MyComponent {...props} />);
sinon.assert.calledOnce(spy);
});
Результат - тест не удалось с AssertError: expected updateSomething to be called once but was called 0 times
, но все три console.log()
напечатаны.
Насколько я понимаю, поскольку я хочу протестировать событие, когда оно установлено, мне нужно шпионить / заглушить его, прежде чем оно даже будет создано, поэтому я должен шпионить на MyComponent.Prototype
. Кроме того, для fetchSomething()
я должен заглушить вызов asyn c и сделать его .resolves()
, чтобы он продолжался.
Но я не мог понять, как он может все еще console.log("updateSomething")
без шпионажа .