gpt4 book ai didi

reactjs - React Jest setInterval 测试覆盖率

转载 作者:行者123 更新时间:2023-12-04 04:17:35 26 4
gpt4 key购买 nike

我正在尝试对功能组件进行一些测试。我在 useEffect 中有一个 setInterval 每隔几秒更改一条消息。对于我的测试 似乎我没有测试 useEffect 中的任何内容。我试过 jest.useFakeTimers();

我还设置了 useState。

组件:

import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import styled from "styled-components";
// Array of strings
import { messages } from "./messages";

export const Wrapper = styled.div`
font-family: 'Lato', sans-serif !important;
box-sizing: border-box;
width: 100%;
display: block;
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
height: 100vh;
h1 {
font-size: 2rem;
color: rgb(100, 100, 100);
}
};
`;

const loadMessage = () => {
// this is the line that is not being tested.
return messages[Math.floor(Math.random() * messages.length)];
};

export const Loader = () => {
const [message, setMessage] = useState("Loading...");

useEffect(() => {
const id = setInterval(() => {
// this is the line that is not being tested.
setMessage(loadMessage());
}, 3000);
return () => clearInterval(id);
}, [message]);

return (
<Wrapper id="login-content">
<Row className="align-items-center h-100">
<Col className="col-md-12 mx-auto">
<div className="container text-center">
<h1 className="loader" data-testid="loader" aria-live="polite">
{message}
</h1>
</div>
</Col>
</Row>
</Wrapper>
);
};

测试:

import React from "react";
import { shallow } from "enzyme";
import { Loader } from "./Loader";

const doAsync = c => {
setTimeout(() => {
c(true);
}, 3000);
};

jest.useFakeTimers();

describe("Loader component", () => {
it("tests state", () => {
const wrapper = shallow(<Loader />);
const message = wrapper.find(".loader").text();

jest.advanceTimersByTime(3000);

const callback1 = () => {
expect(wrapper.find(".loader").text()).not.toMatch(message);
};

doAsync(callback1);

jest.useRealTimers();
});
});

最佳答案

我偶然发现了 enzyme 问题:https://github.com/airbnb/enzyme/issues/2086

useEffect function does not seem to be executed when the component is rendered with shallow.

鉴于此,我必须做的是模拟 UseEffect。

const doAsync = c => {
setTimeout(() => {
c(true);
}, 3000);
};

jest.useFakeTimers();

describe("Loader component", () => {
beforeEach(() => {
const useEffect = jest
.spyOn(React, "useEffect")
.mockImplementation(f => f());
});

it("tests state", done => {
const wrapper = shallow(<Loader />);
const message = wrapper.find(".loader").text();

jest.advanceTimersByTime(3000);

const callback1 = () => {
expect(wrapper.find(".loader").text()).not.toMatch(message);
};

doAsync(callback1);

jest.useRealTimers();
done();
});
});

这使我的测试通过并且我获得了 100% 的覆盖率。

关于reactjs - React Jest setInterval 测试覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60305459/

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