我正在使用 Jest 和 MSW 在 React 中实现前端测试。我想通过使用正常的获取从组件中的模拟 api 接收数据。但是,出现错误
ReferenceError: TextEncoder is not defined
。
代码:
handlers.ts
// /mocks/handlers.ts
import { http, HttpResponse } from "msw";
export const handlers = [
http.get("https://localhost:4000/1/messages", () => {
return HttpResponse.json({
_id: "1",
name: "John Doe",
message: "Hello world!"
})
})
代码:
server.ts
(错误)
// /mocks/server.ts
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
export const server = setupServer(...handlers)
代码:
setupTests.ts
import "@testing-library/jest-dom";
import { server } from "./mocks/server";
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
代码:
component.tsx
useEffect(() => {
fetch("https://localhost:4000/1/messages")
.then(res => res.json())
.then(data => setChatheads(data))
.catch(() => setError("Error fetching messages"));
}, [])
尝试:我尝试添加此代码,就像我从这个上一个问题中读到的那样,但是它仍然不起作用,并且出现了相同的错误。
import { TextEncoder, TextDecoder } from 'util';
Object.assign(global, { TextDecoder, TextEncoder });
我还尝试通过应用上面的类似代码来手动编辑
encoding.js
(“node_modules/whatwg_url/dist/encoding.js”),但是出现了相同的错误。
版本:
期望: 编辑
server.ts
后,模拟的 api 预计可以使用此链接工作并获取:
"https://localhost:4000/1/messages"
它应该返回提供的对象,即:
{
_id: "1",
name: "John Doe",
message: "Hello world!"
}
我必须创建一个 test.environment 文件来模拟该功能。
我的环境是为 ECMAScript 模块配置的,因此在我的笑话配置文件中,我添加了:
testEnvironment: './test.environment.mjs',
然后 test.environment.mjs 文件包含:
import { TestEnvironment } from 'jest-environment-jsdom';
export default class CustomEnvironment extends TestEnvironment {
async setup() {
await super.setup();
// Add globals that are on real browsers and Node 18+, but aren't in Jest's builtin environments.
this.global.Blob = Blob;
this.global.fetch = fetch;
this.global.File = File;
this.global.FormData = FormData;
this.global.Headers = Headers;
this.global.Request = Request;
this.global.Response = Response;
this.global.TextEncoder = TextEncoder;
this.global.TextDecoder = TextDecoder;
}
}
如果您使用的是 commonJS,则只需将文件扩展名更改为 .js 并使环境文件的内容类似于:
const Environment = require("jest-environment-jsdom").default;
module.exports = class CustomTestEnvironment extends Environment {
async setup() {
await super.setup();
this.global.TextEncoder = TextEncoder;
this.global.TextDecoder = TextDecoder;
this.global.Response = Response;
this.global.Request = Request;
}
};