我正在使用垃圾进行本地开发和单元测试。
#API fetch
const { loading, error, data } = useFetch('https://made.up/api/usage')#handler.js
import { rest } from 'msw'
export const handlers = [
rest.get('https://made.up/api/usage', (req, res, ctx) => {
return res(
ctx.status(301),
ctx.json({
id: 1,
firstName: 'John',
}),
)
}),
]#server.js
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
export const server = setupServer(...handlers)#setupTests.js
beforeAll(() => {
server.listen({
onUnhandledRequest: 'warn',
})
})
afterEach(() => {
server.resetHandlers()
})
afterAll(() => {
server.close()
})#App.test.js
import React from "react";
import { rest } from "msw";
import { render, screen } from "@testing-library/react";
import { server } from "../src/mocks/server";
import App from "../src/App";
test("passes", async () => {
render(<App />);
expect(
// Expect the mocked response to be present in the DOM.
await screen.findByText(`{"id":1,"firstName":"John"}`)
).toBeInTheDocument();
});
test("error", async () => {
server.use(
rest.get("https://made.up/api/usage", (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({
error: "error"
})
);
})
);
render(<App />);
expect(
// Expect the mocked error response to be present in the DOM.
await screen.findByText("Error: error}")
).toBeInTheDocument();
});我正在重写API处理程序来测试错误场景。在一起运行时,这两个测试都没有通过。如果我单独运行它们,它们就能正常工作。
我是不是错过了任何一步?或者我们可以用其他方式测试相同API的不同响应,使用MSW?
发布于 2022-04-06 12:08:50
我已经解决了这个问题。
server.use(
rest.get("https://made.up/api/usage", (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({
error: "error"
})
);
})
);上面的代码将永久覆盖API处理程序。如果我们要覆盖一次,则
server.use(
rest.get("https://made.up/api/usage", (req, res, ctx) => {
return res.once(
ctx.status(500),
ctx.json({
error: "error"
})
);
})
);由于这个原因,我的测试不是一起运行的,而是单独运行时工作得很好。
https://stackoverflow.com/questions/71764462
复制相似问题