首页 > 解决方案 > 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?

标签: reactjsunit-testingjestjsenzymespyon

解决方案


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(...);

推荐阅读