gpt4 book ai didi

javascript - 如何使用 Jest/Enzyme 测试 React 中的 keydown 事件?

转载 作者:行者123 更新时间:2023-12-01 00:28:54 25 4
gpt4 key购买 nike

我有以下组件:

import React, { Component } from 'react';

export class Cars extends Component {
constructor(props) {
super(props);
this.state = {
activeSearch: true
};
}

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

escFunction(event) {
if (event.keyCode === 27) this.skipCar();
}

skipCar() {
this.setState({ activeSearch: false });
}

render() {
return <div></div>;
}
}

我编写了以下测试来检查是否调用了该函数:

test('should close', () => {
let events = {};
document.addEventListener = jest.fn((event, cb) => {
events[event] = cb;
});

const wrapper = shallow(<Cars {...props} />);
const instance = wrapper.instance();
const spy = jest.spyOn(instance, 'skipCar');

events.keyDown({ keyCode: 27 });

expect(spy).toHaveBeenCalled();
expect(wrapper.state().activeSearch).toBe(false);
});

但是当我运行此测试时出现错误:

TypeError: events.keyDown is not a function

> 82 | events.keyDown({ keyCode: 27 });
| ^

为什么我会出现这个错误???如何运行此测试来检查方法是否运行?

最佳答案

您应该使用event.keydown({ keyCode: 27 }),那么您的代码就可以正常工作。

这是您的代码的工作单元测试:

index.jsx:

import React, { Component } from 'react';

export class Cars extends Component {
constructor(props) {
super(props);
this.state = {
activeSearch: true
};
this.escFunction = this.escFunction.bind(this);
}

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

escFunction(event) {
if (event.keyCode === 27) this.skipCar();
}

skipCar() {
this.setState({ activeSearch: false });
}

render() {
return <div></div>;
}
}

index.spec.jsx:

import React from 'react';
import { shallow } from 'enzyme';
import { Cars } from './';

const props = {};

test('should close', () => {
let events = {};
document.addEventListener = jest.fn((event, cb) => {
events[event] = cb;
});

const wrapper = shallow(<Cars {...props} />);
const instance = wrapper.instance();
const spy = jest.spyOn(instance, 'skipCar');

events.keydown({ keyCode: 27 });

expect(spy).toHaveBeenCalled();
expect(wrapper.state().activeSearch).toBe(false);
});

单元测试结果:

 PASS  src/stackoverflow/58748367/index.spec.jsx (7.988s)
✓ should close (10ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.214s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58748367

关于javascript - 如何使用 Jest/Enzyme 测试 React 中的 keydown 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58748367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com