Reactjs Jest spy on component';s性质法

Reactjs Jest spy on component';s性质法,reactjs,unit-testing,jestjs,enzyme,spyon,Reactjs,Unit Testing,Jestjs,Enzyme,Spyon,我试图测试componentDidMount调用的init方法中是否添加了一个事件,但只有当组件的属性设置为“true”时,才会添加该事件,因此我想监视addEventHandler方法并调用“toBeCalledWith('eventName')”,因此我有如下内容: export interface IMyComponentProps{ flag?: boolean; } export class MyComponent extends Component<IMyCompon

我试图测试componentDidMount调用的init方法中是否添加了一个事件,但只有当组件的属性设置为“true”时,才会添加该事件,因此我想监视addEventHandler方法并调用“toBeCalledWith('eventName')”,因此我有如下内容:

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);
        }
    }
}
test("Test 1", () => {
   const spyInit = jest.spyOn(MyComponent.prototype, "init");
   wrapper = mount(
      <MyComponent />
   );

   expect(spyInit).toBeCalled();
})

有什么建议吗?

您需要将
标志
道具传递给组件。例如

index.ts

从'react'导入{Component};
导出接口IMyComponentProps{
标志?:布尔值;
}
导出类MyComponent扩展组件{
私有myProperty!:HTMLElement;
公共组件didmount(){
this.init();
}
公共渲染(){
返回null;
}
私有init(){
如果(此.props.flag){
this.myProperty.addEventListener('event',()=>null,false);
}
}
}
index.test.tsx

从“/”导入{MyComponent};
从“酶”导入{mount};
从“React”导入React;
描述('60714899',()=>{
它('应该添加事件侦听器',()=>{
const spyInit=jest.spyOn(MyComponent.prototype作为任何“init”);
常量mMyProperty={addEventListener:jest.fn()}如有;
MyComponent.prototype['myProperty']=mMyProperty;
const wrapper=mount();
expect(spyInit).toBeCalled();
expect(mMyProperty.addEventListener).toBeCalledWith('event',expect.any(Function),false);
});
它('不应添加事件侦听器',()=>{
const spyInit=jest.spyOn(MyComponent.prototype作为任何“init”);
常量mMyProperty={addEventListener:jest.fn()}如有;
MyComponent.prototype['myProperty']=mMyProperty;
const wrapper=mount();
expect(spyInit).toBeCalled();
expect(mMyProperty.addEventListener).not.toBeCalled();
});
});
100%覆盖率的单元测试结果:

PASS stackoverflow/60714899/index.test.tsx
60714899
✓ 应添加事件侦听器(42ms)
✓ 不应添加事件侦听器(2ms)
-----------|---------|----------|---------|---------|-------------------
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s
-----------|---------|----------|---------|---------|-------------------
所有文件| 92.31 | 100 | 80 | 100 |
index.tsx | 92.31 | 100 | 80 | 100 |
-----------|---------|----------|---------|---------|-------------------
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:4.77秒,估计10秒

源代码:

并没有完全回答这个问题,但是从jasmine迁移到jest的人可能会发现这很有用

jest.spyOn(component, 'propertyName', 'get').mockReturnValue(...);
这相当于jasmine的间谍属性:

jasmine.spyOnProperty(component, 'propertyName').and.returnValue(...);

我发现这很有帮助,即使我没有迁移:D。它与问题的标题相匹配。让茉莉花发挥作用不是一个好主意,因为这个问题与此无关。我觉得上面没有这个,所以你可以创建一个问题,然后自己回答。@WilliMentzel:我在寻找这个答案时发现了这个问题。但是这个答案不在那里,所以我修正了它。谢谢你这么做:)谢谢你的茉莉花参考,这个解决方案现在非常有意义。
jasmine.spyOnProperty(component, 'propertyName').and.returnValue(...);