我正在尝试为需要在其componentWillMount方法中完成异步操作的React组件编写测试。componentWillMount调用作为prop传递的函数,该函数返回promise,然后在测试中模拟该函数。
这可以正常工作,但是如果在调用setImmediate或时测试失败process.nextTick,则Jest不会处理该异常,并且该异常会过早退出。在下面,您可以看到我什至试图捕获此异常,但无济于事。
我如何使用像setImmediate或者nextTick用玩笑?这个问题的公认答案是我试图实现失败的目标:React Enzyme-Test`componentDidMount` Async Call。
it('should render with container class after getting payload', (done) => {
let resolveGetPayload;
let getPayload = function() {
return new Promise(function (resolve, reject) {
resolveGetPayload = resolve;
});
}
const enzymeWrapper = mount(<MyComponent getPayload={getPayload} />);
resolveGetPayload({
fullname: 'Alex Paterson'
});
try {
// setImmediate(() => {
process.nextTick(() => {
expect(enzymeWrapper.hasClass('container')).not.toBe(true); // Should and does fail
done();
});
} catch (e) …Run Code Online (Sandbox Code Playgroud) 我正在使用 Jest/Enzyme 来测试 React/TypeScript 应用程序,并且我很难尝试编写一个测试来断言按钮是否在一段时间后显示:
这是要测试的组件的非常简化的版本:
import { StyledNotifyButton } from './styles'; //style-component element
const SomeComponent = (): ReactElement => {
const [showNotifyButton, toggleNotifyButton] = useState(false);
useEffect(() => {
setTimeout(() => toggleNotifyButton(true), 5000);
}, [toggleNotifyButton]);
return (
<div>
<StyledNotifyButton visible={showNotifyButton} />
</div>
);
Run Code Online (Sandbox Code Playgroud)
这是测试:
describe('< FailingTest >', () => {
let wrapper: ReactWrapper;
beforeAll(() => {
wrapper = mount(<SomeComponent />);
});
it('should display the notify button only after X seconds', done => {
let notifyButton = wrapper.find('StyledNotifyButton');
jest.spyOn(React, 'useEffect').mockImplementation(f => …Run Code Online (Sandbox Code Playgroud)