gpt4 book ai didi

javascript - 使用 useEffect 和 jest.useFakeTimer() 进行测试

转载 作者:行者123 更新时间:2023-11-30 19:35:06 25 4
gpt4 key购买 nike

我正在尝试在这里创建简单的复习组件

Refresher.js

import { useEffect } from 'react';

const Refresher = ({ onRefresh }) => {
useEffect(() => {
const id = setInterval(onRefresh, 60000);
return () => {
clearInterval(id);
};
}, [onRefresh]);

return null;
};

export default Refresher;

但是,当我尝试使用 jest.useFakeTimers() 对其进行测试时,不知何故它不起作用。即使在 jest.runOnlyPendingTimers()

之后也不会调用 stub
import React from 'react';
import renderer from 'react-test-renderer';
import Refresher from '../Refresher';

describe('Refresher', () => {
test('should refresh the result every 60 seconds', () => {
jest.useFakeTimers();

const onRefreshSpy = jest.fn();

const refresher = renderer.create(<Refresher onRefresh={onRefreshSpy} />);

expect(onRefreshSpy).not.toHaveBeenCalled();
jest.runOnlyPendingTimers();
refresher.update(); // Trying force update here

expect(onRefreshSpy).toHaveBeenCalled();
});
});

如果没记错的话,如果组件没有更新,间隔将不会运行,所以我尝试使用 refresher.update(),但似乎它并没有真正起作用。

有人知道如何解决这里的测试问题吗?

最佳答案

您只需要模拟 useLayoutEffect 而不是 useEffect。请参阅问题 here

describe('Refresher', () => {
beforeAll(() => jest.spyOn(React, 'useEffect').mockImplementation(React.useLayoutEffect))
test('should refresh the result every 60 seconds', () => {
jest.useFakeTimers();
const onRefreshSpy = jest.fn();
const refresher = renderer.create(<Refresher onRefresh={onRefreshSpy} />);
expect(onRefreshSpy).not.toHaveBeenCalled();
jest.runOnlyPendingTimers();
expect(onRefreshSpy).toHaveBeenCalled();
});
});

关于javascript - 使用 useEffect 和 jest.useFakeTimer() 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56024450/

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