【发布时间】:2020-11-26 13:44:23
【问题描述】:
我有一个 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(),我必须存根异步调用并使其成为.resolves() 以让它继续。
但我不明白它怎么还能console.log("updateSomething") 不被监视。
【问题讨论】:
标签: javascript reactjs testing enzyme sinon