gpt4 book ai didi

reactjs - 如何测试由在 useEffect 上触发的 SetTimeout 修改的组件样式?

转载 作者:行者123 更新时间:2023-12-05 00:53:39 24 4
gpt4 key购买 nike

我正在使用 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>
);

这是测试:

 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 => f());
expect(notifyButton.prop('visible')).toBe(false);

jest.useFakeTimers();
setTimeout(() => {
wrapper.update();
notifyButton = wrapper.find('NotifyButton');
expect(notifyButton.prop('visible')).toBe(true);
wrapper.unmount();
done();
}, 5000);
jest.runAllTimers();
});

我已经尝试使用 fakeTimers、advanceTimersByTime、runAllTimers,如 Just Timer Mocks 中所述。

我已经尝试过 setTimeouts,如 here 所述

手动触发 useEffect,如 herehere

还有很多其他方法......但我总是得到

expect(received).toBe(expected) // Object.is equality

Expected: true
Received: false

关于如何在超时后正确获得可​​见性变化的任何想法?谢谢!

最佳答案

组件挂载后,会执行useEffectsetTimeout,需要使用jest.useFakeTimers(implementation?: 'modern' | 'legacy')在安装组件之前。

使用 jest.runOnlyPendingTimers()

Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point)

jest.advanceTimersByTime(msToRun) .

此外,我们需要将渲染它并执行更新的代码封装在 act() 中。调用,所以把 jest.runOnlyPendingTimers() 放在 act() 中。

最后,我们需要调用 wrapper.update() 来确保状态反射(reflect)到 View 中。

例如

SomeComponent.tsx:

import React, { ReactElement, useEffect, useState } from 'react';
import { StyledNotifyButton } from './styles';

export const SomeComponent = (): ReactElement => {
const [showNotifyButton, toggleNotifyButton] = useState(false);

useEffect(() => {
setTimeout(() => {
toggleNotifyButton(true);
}, 5000);
}, [toggleNotifyButton]);

console.log('showNotifyButton: ', showNotifyButton);

return (
<div>
<StyledNotifyButton visible={showNotifyButton} />
</div>
);
};

styles.tsx:

import React from 'react';

export function StyledNotifyButton({ visible }) {
return <button>click me</button>;
}

SomeComponent.test.tsx:

import { mount, ReactWrapper } from 'enzyme';
import React from 'react';
import { act } from 'react-dom/test-utils';
import { SomeComponent } from './SomeComponent';

describe('67440874', () => {
let wrapper: ReactWrapper;

beforeAll(() => {
jest.useFakeTimers();
wrapper = mount(<SomeComponent />);
});
it('should pass', () => {
let notifyButton = wrapper.find('StyledNotifyButton');
expect(notifyButton.prop('visible')).toBe(false);
act(() => {
jest.runOnlyPendingTimers();
});
wrapper.update();
expect(wrapper.find('StyledNotifyButton').prop('visible')).toBeTruthy();
});
});

测试结果:

 PASS  examples/67440874/SomeComponent.test.tsx
67440874
✓ should pass (8 ms)

console.log
showNotifyButton: false

at SomeComponent (examples/67440874/SomeComponent.tsx:13:11)

console.log
showNotifyButton: true

at SomeComponent (examples/67440874/SomeComponent.tsx:13:11)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.721 s

软件包版本:

"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"jest": "^26.6.3",
"jest-environment-enzyme": "^7.1.2",
"jest-enzyme": "^7.1.2",

关于reactjs - 如何测试由在 useEffect 上触发的 SetTimeout 修改的组件样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67440874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com