我将使用Enzyme 来测试 react 组件的行为。
Enzyme 是一个用于 React 的 JavaScript 测试实用程序,可以更轻松地测试 React 组件的输出
您可以使用浅包装器的.invoke(invokePropName)(...args) => Any 来调用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