reactjs - 用 jest 和酶窥探 React 功能组件方法;无法窥探原始值
问题描述
我正在尝试测试一个 React 组件并确保当它的按钮被点击时,正确的方法被调用。但是,当我尝试运行测试并尝试监视该方法时,我收到以下消息:
错误:无法窥探原始值;给定的未定义
如何测试单击按钮时是否调用了正确的方法?谢谢!
示例组件.jsx:
import * as React from 'react';
const SampleComponent = () => {
const sampleMethod = () => {
console.log('hello world');
};
return <button onClick={sampleMethod} type="button">Click Me</button>;
};
export default SampleComponent;
sampleComponent.test.jsx:
import * as React from 'react';
import { shallow } from 'enzyme';
import SampleComponent from './sample';
test('testing spy', () => {
const spy = jest.spyOn(SampleComponent.prototype, 'sampleMethod');
const wrapper = shallow(<SampleComponent />);
wrapper.find('button').simulate('click');
expect(spy).toHaveBeenCalled();
});
解决方案
该错误意味着,sampleMethod
您在功能组件SampleComponent
中定义的功能未在SampleComponent.prototype
. 所以SampleComponent.prototype.sampleMethod
,undefined
开玩笑不能监视一个undefined
值。
所以测试事件处理程序的正确方法sampleMethod
是这样的:
index.spec.tsx
:
import React from 'react';
import SampleComponent from './';
import { shallow } from 'enzyme';
describe('SampleComponent', () => {
test('should handle click correctly', () => {
const logSpy = jest.spyOn(console, 'log');
const wrapper = shallow(<SampleComponent></SampleComponent>);
const button = wrapper.find('button');
expect(button.text()).toBe('Click Me');
button.simulate('click');
expect(logSpy).toBeCalledWith('hello world');
});
});
我们可以监视console.log
,断言它是否被调用。
覆盖率 100% 的单元测试结果:
PASS src/react-enzyme-examples/02-react-hooks/index.spec.tsx
SampleComponent
✓ should handle click correctly (19ms)
console.log node_modules/jest-mock/build/index.js:860
hello world
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.036s
依赖版本:
"react": "^16.11.0",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.15.1",
"jest": "^24.9.0",
"jest-environment-enzyme": "^7.1.1",
"jest-enzyme": "^7.1.1",
推荐阅读
- list - Flutter - 列表中的可点击 OnTap
- javascript - 如何在 JS 中解析表情符号?
- php - 在 Laravel 应用程序中删除无样式内容的 flash
- sql-server - Azure SQL 查询如何返回数据库条目的旧值和新值?
- android - 如何通过选择语言更改为 RTL
- performance - 如何衡量回调的处理时间和瓶颈?
- c# - 有没有办法通过 IIS 和 HTTPContext 使用 ASP.net 身份验证?
- python - Pyqt5如何在渲染地图上的每个特定时间生成标记?
- jquery - Rails ActionController::RoutingError 用于 AJAX/JQUERY 调用控制器
- azure-rtos - ThreadX 事件标志