我正在嘗試在我的 App 組件中模擬一個變數 ( auth ),因為它正在執行條件渲染。我應該如何在不嘗試匯出變數本身的情況下執行此操作?用各種解決方案嘗試了幾天,但我似乎無法解決它,現在我被卡住了。
應用程式.js
import React from "react";
import { useRoutes } from "react-router-dom";
import Routing from "./routes";
import useAuth from "./hooks/useAuth";
import SplashScreen from "./components/splashScreen/SplashScreen";
const App = () => {
const content = useRoutes(Routing());
const auth = useAuth();
return (
<>
{auth.isInitialized ? content : <SplashScreen />}
</>
);
};
export default App;
應用程式.test.js
import React from "react";
import { mount } from "enzyme";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
describe("App Unit Tests", () => {
let wrapper;
beforeEach(() => {
wrapper = mount(
<BrowserRouter>
<App />
</BrowserRouter>
);
});
it("App should render", () => {
expect(wrapper.length).toEqual(1);
});
//Below fails
it("should render splashscreen", () => {
jest.mock("./hooks/useAuth", () => ({
isInitialized: false,
}));
expect(wrapper.length).toEqual(1);
});
it("should render content", () => {
jest.mock("./hooks/useAuth", () => ({
isInitialized: true,
}));
expect(wrapper.length).toEqual(1);
});
});
uj5u.com熱心網友回復:
你可以這樣做:
jest.mock('./hooks/use-auth', () => ({
isInitialized: true
});
這基本上意味著use-auth回傳一個具有inInitialized屬性的物件
uj5u.com熱心網友回復:
取而代之的是auth,useAuth鉤子應該被模擬成一個mockUseAuth具有isInitializedgetter的物件(比如)。getter 應該回傳一個mockIsInitialized值,該值可以根據每個測驗用例進行更改。像這樣的事情:
let mockIsInitialized = true;
let mockUseAuth = {
isAuthenticated: true
};
Object.defineProperty(mockUseAuth, 'isInitialized', {
get: jest.fn(() => mockIsInitialized)
});
jest.mock('./hooks/use-auth', () => {
return jest.fn(() => (mockUseAuth))
})
describe("App Unit Tests", () => {
let wrapper;
beforeEach(() => {
wrapper = mount(
<BrowserRouter>
<App />
</BrowserRouter>
);
});
it("App should render", () => {
expect(wrapper.length).toEqual(1);
});
it("should render splashscreen", () => {
mockIsInitialized = false;
expect(wrapper.length).toEqual(1);
});
it("should render content", () => {
mockIsInitialized = true;
expect(wrapper.length).toEqual(1);
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/403136.html
標籤:
下一篇:基于反應狀態的div條件渲染
