我有一个带有剧作家测试的Nextjs项目,对于模拟API,我使用的是Mock Service Worker (MSW)库。
我已经安装和设置了所有内容,而且当我在_app.tsx文件中运行MSW工作人员时,将正确地模拟API .。
下面是我的http://localhost:500/user index.tsx,它根据API对index.tsx的调用显示"John“或"Failed”。
import React, { useState } from "react";
export default function Home() {
const [user, setUser] = useState<any>();
const [error, setError] = useState<string>();
const fetchUser = async () => {
try {
const response = await fetch("http://localhost:5000/user");
const user = await response.json();
setUser(user);
} catch (error) {
console.log(error);
setError("Failed");
}
};
return (
<div>
{error && <div data-testid="content">{error}</div>}
{user && <div data-testid="content">{user.name}</div>}
<button data-testid="btn" onClick={() => fetchUser()}>
Submit
</button>
</div>
);
}但是,当我使用MSW工作人员并在剧作家测试文件中定义请求处理程序时,测试失败。下面是剧作家的测试文件:
import { test, expect } from "@playwright/test";
import { setupWorker, rest } from "msw";
test.describe("Request tests", () => {
test.beforeAll(() => {
if (typeof window !== "undefined") {
const worker = setupWorker(
rest.get("http://localhost:5000/user", (req, res, ctx) => {
return res(ctx.status(200), ctx.json({ name: "John" }));
})
);
worker.start();
}
});
test.beforeEach(async ({ page }) => {
await page.goto("http://localhost:3000/");
});
test("should display John when submit is clicked", async ({ page }) => {
await page.locator("[data-testid=btn]").click();
await expect(page.locator("[data-testid=content]")).toContainText("John");
});
});尽管我已经定义了MSW请求处理程序,但是测试失败了,但是它没有模拟响应,因此我们没有在页面上获得文本John。
请求处理程序不能工作的原因是什么?我是不是用错了?
这是指向github回购- https://github.com/rajmasha/nextjs-testing的链接
发布于 2022-04-05 12:44:40
我打赌它不起作用,因为您在“剧作家”上下文中启动了您的工作人员,但在浏览器中却没有。因此,页面永远不会启动worker,也无法拦截任何请求。而且似乎剧作家只支持服务工作者。
现在看来,您应该用基于服务器的msw解决方案来包装剧作家的嘲笑。
我找到了这个包裹https://github.com/valendres/playwright-msw。你可以在这里核实一下
https://stackoverflow.com/questions/71651917
复制相似问题