这是我的代码示例
// App.js
import React, { Suspense, lazy } from "react";
const Loader = () => <div data-testid="loader">Loading...</div>
const Login = lazy(() => import("./Login"));
function App() {
return (
<Suspense fallback={<Loader />}>
<Login />
</Suspense>
);
}
export default App;
// Login.js
import React from 'react';
const Login = () => <div data-testid="login">Login</div>
export default Login
// App.test.js
import React from 'react';
import { render, waitForElementToBeRemoved, cleanup } from '@testing-library/react';
import App from './App';
describe('App when user is not signed in', () => {
it("should redirect to login page", async () => {
beforeEach(() => jest.resetAllMocks())
const { getByTestId, getByText } = render(<App />);
await waitForElementToBeRemoved(() => getByTestId('loader'))
const linkElement = getByText(/Login/i);
expect(linkElement).toBeInTheDocument();
});
})
describe('App with User Logged in as Admin', () => {
it("redirect to login page", async () => {
beforeEach(() => {
// will set local storage for auth token
// for a logged in user
})
let container = document.createElement('div')
const { getByTestId, getByText } = render(<App />, {
container
});
await waitForElementToBeRemoved(() => getByTestId('loader'))
const linkElement = getByText(/Login/i);
expect(linkElement).toBeInTheDocument();
});
})
我遇到的问题是,我希望在运行第二次测试时拥有加载器,但它不存在因此引发错误。
我想知道为什么加载器没有在第二个测试中呈现,它立即呈现登录页面。我怀疑第一个测试会影响第二个测试,但问题是为什么。
我在这里创建了一个对此问题的回复。https://repl.it/@tibetegya/Create-React-App