【发布时间】:2022-01-18 16:37:43
【问题描述】:
我想用单元测试覆盖下面的代码:
export class DataTrack extends Component<DataTrackProps> {
componentDidMount() {
this.setData();
if (this.props.enableDataTrack) {
this.pushData();
}
}
private setData() {
window.globalData = {
app_platform : "I"
}
}
private getData() {
this.dataTrack= {
command: "EVENT",
name: "data",
data: {
app_embed_name : "it"
}
};
return this.dataTrack;
}
private pushData() {
window.analyticsData = window.analyticsData || [];
window.analyticsData .push(this.getData());
}
}
并开始使用以下测试覆盖componentDidMount:
it("should run the methods in the componentDidMount", () => {
const props: DataTrackProps= {
enableDataTrack: true,
};
const setDataOnMount = jest.spyOn(DataTrack.prototype, 'setData'); // spy
const wrapper = shallow(<DataTrack{...props} />); // create
expect(setDataOnMount ).toHaveBeenCalledTimes(1); // test
});
但是我得到了错误:
Argument of type '"setData"' is not assignable to parameter of type 'FunctionPropertyNames<Required<DataTrack>>'.
我也不知道如何使用 Jest/Enzyme 测试方法 setData、getData 和 pushData。
有人可以帮我解决这个问题吗?
如何覆盖componentDidMount 中的方法和方法自身?
【问题讨论】:
标签: reactjs unit-testing jestjs enzyme