Jest测试条件响应



我有数据

const data = {
animal: 'cat',
isBlack: true
}

如果猫是黑色的,我希望我的组件渲染一些文本,如果猫不是黑色的,则不渲染。我有几个测试

describe('About', () => {
const data = {
animal: 'cat',
isBlack: true
}
beforeEach(() => {
fetchMock.getOnce('/api/animals', {data});
});
afterEach(() => {
fetchMock.reset();
expect(fetchMock.done()).toBe(true);
});
it('should render with first text', () => {
expect(instance.getByText('Black Cats are awesome')).toBeVisible();
})
it('should render with second text', () => {
expect(instance.getByText('Black Cats are my favourite')).toBeVisible();
})
it('should render with second text', () => {
expect(instance.getByText('Black Cats rule')).toBeVisible();
})
it('should render no text', () => {
expect(instance.queryByText('Black Cats rule')).toBeNull();
})
)

所以基本上只要isBlack为false,就不应该呈现任何文本。所以,我现在所拥有的,我在每个测试中都有fetchMock,我的愿望是在每个测试之前都运行fetchMok,并相应地更改测试中错误情况的响应。有办法吗?

我看不到yout代码,但假设它更像这样:

  • 组件CatComponent
import React from "react";
import { fetchData } from "./fetchCatData";
const CatComponent = () => {
const [data, setData] = React.useState({});
React.useEffect(() => {
const fetchCatData = async () => {
const data = await fetchData();
setData(data);
};
fetchCatData();
}, []);
return (
<div>
{data && data.isBlack && (
<>
<p>Black Cats are awesome</p>
<p>Black Cats are my favourite</p>
<p>Black Cats rule</p>
<p>Black Cats rule</p>
</>
)}
</div>
);
};
export default CatComponent;
  • 获取api:fetchCatData
export const fetchData = async () => {
return Promise.resolve({ animal: 'dog', isBlack: false })
}

我们可以进行这样的测试:

import { render, screen, waitFor } from "@testing-library/react";
import CatComponent from "../CatComponent";
const mockFetchData = jest.fn();
jest.mock("../fetchCatData", () => ({
fetchData: () => mockFetchData(),
}));
describe("should work tests", () => {
it("no text", async () => {
render(<CatComponent />);
await waitFor(() => {
expect(
screen.queryByText("Black Cats are awesome")
).not.toBeInTheDocument();
});
});
it('texts present', async () => {
mockFetchData.mockResolvedValue({ isBlack: true })
render(<CatComponent />);
await waitFor(() => {
expect(
screen.getByText("Black Cats are awesome")
).toBeInTheDocument();
});
expect(screen.getByText('Black Cats are my favourite')).toBeInTheDocument();
})
});

相关内容

  • 没有找到相关文章

最新更新