[英]How to test onClose prop with Jest and ReactJs
我有一个看起来像这样的组件,当单击按钮时,模式打开,当单击 X 按钮时,按下鼠标或按下 esc 键模式关闭并调用onClose
function,但是,Jest 报告说setIsOpen(false);
不包括在内。
const MyComponent = () => {
const [isOpen, setIsOpen] = useState(false);
return (
<div className="container">
<button
onClick={() => {
setIsOpen(true);
}}
/>
<Flow
isOpen={isOpen}
onClose={() => {
setIsOpen(false);
}}
/>
</div>
);
};
我如何测试setIsOpen(false);
被调用? 我尝试了 mocking useState
并检查它是否被调用,但是,这搞砸了setIsOpen(true);
在按钮中,作为模拟,模式不会打开。
有任何想法吗?
我将使用Enzyme来测试反应组件的行为。
Enzyme 是一款用于 React 的 JavaScript 测试实用程序,可以更轻松地测试 React 组件的 output
您可以使用.invoke(invokePropName)(...args) => 任何浅层包装器来调用Flow
组件的onClose()
方法。
例如
MyComponent.tsx
:
import React, { useState } from 'react';
import { Flow } from './Flow';
export const MyComponent = () => {
const [isOpen, setIsOpen] = useState(false);
return (
<div className="container">
<button
onClick={() => {
setIsOpen(true);
}}
/>
<Flow
isOpen={isOpen}
onClose={() => {
setIsOpen(false);
}}
/>
</div>
);
};
Flow.tsx
import React from 'react';
export function Flow({ isOpen, onClose }) {
if (!isOpen) return null;
return <div onClick={onClose}>close</div>;
}
MyComponent.test.tsx
:
import React from 'react';
import { shallow } from 'enzyme';
import { MyComponent } from './MyComponent';
import { Flow } from './Flow';
describe('67027129', () => {
it('should set open to true', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find(Flow).prop('isOpen')).toBeFalsy();
wrapper.find('button').simulate('click');
expect(wrapper.find(Flow).prop('isOpen')).toBeTruthy();
});
it('should set open to false', () => {
const wrapper = shallow(<MyComponent />);
wrapper.find('button').simulate('click');
expect(wrapper.find(Flow).prop('isOpen')).toBeTruthy();
wrapper.find(Flow).invoke('onClose')();
expect(wrapper.find(Flow).prop('isOpen')).toBeFalsy();
});
});
单元测试结果:
PASS examples/67027129/MyComponent.test.tsx (10.173 s)
67027129
✓ should set open to true (37 ms)
✓ should set open to false (19 ms)
-----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------------|---------|----------|---------|---------|-------------------
All files | 76.92 | 0 | 75 | 81.82 |
Flow.tsx | 40 | 0 | 0 | 50 | 3-4
MyComponent.tsx | 100 | 100 | 100 | 100 |
-----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 10.908 s, estimated 13 s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.