reactjs - Jest spy on component's property method
问题描述
I'm trying to test if an event has been added in the init method called by componentDidMount, but that event is going to be added only if a component's attribute is set in "true" so I want to spy on the addEventHandler method and call the "toBeCalledWith('eventName')" so I have something like this:
export interface IMyComponentProps{
flag?: boolean;
}
export class MyComponent extends Component<IMyComponentProps> {
private myProperty: HTMLElement;
public componentDidMount() {
this.init();
}
private init() {
if (this.props.flag) {
this.myProperty.addEventListener("event", arg2, arg3);
}
}
}
Then I have my test looking like this:
test("Test 1", () => {
const spyInit = jest.spyOn(MyComponent.prototype, "init");
wrapper = mount(
<MyComponent />
);
expect(spyInit).toBeCalled();
})
but the test above does not cover if the addEventListener is called or not so I'm trying different ways like following, without success:
const spyAddListener = jest.spyOn(MyComponent.prototype, "myProperty.addEventHandler");
const spyAddListener = jest.spyOn(MyComponent.instance().myProperty, "addEventHandler");
const spyAddListener = jest.spyOn(MyComponent.prototype.myProperty, "addEventHandler");
any suggestion?
解决方案
Not exactly answering the question, but people who are migrating from jasmine to jest may find this useful.
jest.spyOn(component, 'propertyName', 'get').mockReturnValue(...);
This is an equivalent to jasmine's spyOnProperty
:
jasmine.spyOnProperty(component, 'propertyName').and.returnValue(...);
推荐阅读
- excel - Excel-VBA 将数据从一个工作表复制到另一个工作表并粘贴到新行
- javascript - 在 chrome 中显示选项卡蓝点
- typescript - 在 Typescript 中定义函数类型、函数接口
- vba - 合并两个不同年份的数据集
- java - 如何在 vaadin 进度条中使用整数值?
- eclipse - 带有 SonarLint 的 Eclipse 崩溃,OutOfMemory 处理特定的有问题的类
- css - 使内联元素包含换行符
- git - TortoiseGit 可以使用 Google Cloud Source 存储库的存储库吗?
- c# - 发布时 SOAP UI 不返回预期的输出
- php - 将文件上传到谷歌云存储(php curl)