如何在测试时触发功能组件的卸载?
How to trigger unmounting of functional components while testing?
我使用“useEffect”实现了功能组件中“componentWillUnmount”的功能。如何在使用 Jest/Enzyme?
测试组件时触发它
我的组件:
const myComp = () => {
useEffect(() => () => {
console.log('Unmounted');
}, []);
return <div>Test</div>;
}
根据这个issue, we know that shallow
render doesn't support the useEffect
hook. We need to use mount
and call .unmount()方法手动。
例如
index.tsx
:
import React, { useEffect } from 'react';
export const MyComp = () => {
useEffect(
() => () => {
console.log('Unmounted');
},
[]
);
return <div>Test</div>;
};
index.test.tsx
:
import React from 'react';
import { mount } from 'enzyme';
import { MyComp } from './';
describe('67384129', () => {
it('should pass', () => {
const wrapper = mount(<MyComp />);
wrapper.unmount();
});
});
测试结果:
PASS examples/67384129/index.test.tsx (8.233 s)
67384129
✓ should pass (53 ms)
console.log
Unmounted
at examples/67384129/index.tsx:6:15
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.121 s
包版本:
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"react": "^16.14.0"
"jest": "^26.6.3",
"jest-environment-enzyme": "^7.1.2",
"jest-enzyme": "^7.1.2",
如果您使用的是 react-testing-library 那么:
const { unmount } = render(<Component />);
unmount();
我使用“useEffect”实现了功能组件中“componentWillUnmount”的功能。如何在使用 Jest/Enzyme?
测试组件时触发它我的组件:
const myComp = () => {
useEffect(() => () => {
console.log('Unmounted');
}, []);
return <div>Test</div>;
}
根据这个issue, we know that shallow
render doesn't support the useEffect
hook. We need to use mount
and call .unmount()方法手动。
例如
index.tsx
:
import React, { useEffect } from 'react';
export const MyComp = () => {
useEffect(
() => () => {
console.log('Unmounted');
},
[]
);
return <div>Test</div>;
};
index.test.tsx
:
import React from 'react';
import { mount } from 'enzyme';
import { MyComp } from './';
describe('67384129', () => {
it('should pass', () => {
const wrapper = mount(<MyComp />);
wrapper.unmount();
});
});
测试结果:
PASS examples/67384129/index.test.tsx (8.233 s)
67384129
✓ should pass (53 ms)
console.log
Unmounted
at examples/67384129/index.tsx:6:15
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.121 s
包版本:
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"react": "^16.14.0"
"jest": "^26.6.3",
"jest-environment-enzyme": "^7.1.2",
"jest-enzyme": "^7.1.2",
如果您使用的是 react-testing-library 那么:
const { unmount } = render(<Component />);
unmount();