[英]Not sure how to write a test case for conditionally rendered ReactJS component
我的應用程序最初使用組件內的加載占位符呈現,5 秒后呈現不同的元素。 我想用笑話和酶來測試這個組件。
我的問題是,當我測試它和 console.log(wrapper.debug()) 時,它只顯示加載部分。
現在我的問題是如何對條件部分進行單元測試。
我的 App.js
import React,{useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';
const App = () => {
const [loading, setLoading] = useState(true);
useEffect(()=>{
setTimeout(() => {
setLoading(false)
}, 5000);
},[])
if(loading){
return <span>loading....</span>
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
我的 App.test.js
import React from "react";
import App from "./App";
import { shallow } from "enzyme";
describe("app component", () => {
it("loading state", () => {
const setState = jest.fn();
const useStateMock = (initState) => [initState, setState];
jest.spyOn(React, "useState").mockImplementation(useStateMock);
jest.spyOn(React, "useEffect").mockImplementation(setState);
const wrapper = shallow(<App />);
const result = wrapper.find("#abc");
result.simulate("click");
wrapper.update();
console.log(wrapper.debug());
expect(setState).toHaveBeenCalledWith(false);
});
});
您可以嘗試使用: jest.setTimeout(6000)
import React from "react";
import App from "./App";
import { shallow } from "enzyme";
describe("app component", () => {
it("loading state", () => {
const setState = jest.fn();
const useStateMock = (initState) => [initState, setState];
jest.spyOn(React, "useState").mockImplementation(useStateMock);
jest.spyOn(React, "useEffect").mockImplementation(setState);
const wrapper = shallow(<App />);
const result = wrapper.find("#abc");
result.simulate("click");
wrapper.update();
jest.setTimeout(6000)
console.log(wrapper.debug());
expect(setState).toHaveBeenCalledWith(false);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.