我正在测试一个与Headers
类交互的函数。不确定我的测试在技术上是否福尔斯 * 单元 * 测试的类别,但这应该不相关。
当我运行测试时,我看到了臭名昭著的错误:
引用错误:未定义标头
我确信这是因为测试是在非浏览器环境中执行的。
我的问题是:* 如何在浏览器环境中执行测试,因为我根本不想模拟Headers
类?***
$ yarn test
yarn run v1.12.3
$ jest
FAIL __tests__/request-init-spec.ts
requestInit
× should work (9ms)
● requestInit › should work
ReferenceError: Headers is not defined
13 | describe(requestInit.name, () => {
14 | it('should work', () => {
> 15 | const headers = new Headers();
| ^
16 | headers.append('H1', 'V1');
17 |
18 | const requestInit: RequestInit = {
at Object.it (__tests__/request-init-spec.ts:15:21)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 4.574s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
1条答案
按热度按时间wmtdaxz31#
我通过将环境从
node
更改为jsdom
来修复。另一个解决方案是
另一种解决方案在此提出'ReferenceError: Headers is not defined' when using Headers in a server side rendered react project
TLDR
如果你需要更多的上下文,请阅读这个github问题,其中有300条评论和潜在的解决方案
https://github.com/jestjs/jest/issues/2549