CrazySynthax
CrazySynthax

Reputation: 14998

Enzyme: how to test a key down?

I have a React application that reacts to a keypress of Escape. This is the code in the application:

componentDidMount(){
        document.addEventListener("keydown", this.escFunction.bind(this), false);
    }

In the test code I write the following statement:

wrapper.find('document').simulate('keyDown', {keyCode: 27});

I got an error:

Method “simulate” is only meant to be run on a single node. 0 found instead.

I also tried:

wrapper.simulate('keyDown', {keyCode: 27});

and it seems that application didn't react to escape click.

Upvotes: 2

Views: 2590

Answers (1)

Yogendra Chauhan
Yogendra Chauhan

Reputation: 825

You are getting this error Method “simulate” is only meant to be run on a single node. 0 found instead. means the container is not found.

You should check this first to ensure you are getting the node:

const container = wrapper.find(".class_name");
expect(container.length).to.equal(1);

or this maybe be loading asynchronously that's why, you are not getting the node. Then you should try with setTimeout function to get the node.

Inside setTimeout function call this:

container.simulate('keydown', {key: 'Escape', keyCode: 27, which: 27});

May be this helps.

Upvotes: 1

Related Questions