JEST Express错误:跨原点http://localhost禁止



在使用npm run test执行测试时,我在Express中使用JEST时遇到错误。

console.error
Error: Cross origin http://localhost forbidden

我见过类似CORS错误的帖子-错误:交叉原点http://localhost被禁止的没有工作答案

这是我的测试:

const app = require('../app');
const request = require("supertest");
const enjoyService = require('../services/enjoy.service');
describe('/enjoy', () => {
describe("/cinema/:city", () => {
test('Status is OK', () => {
return enjoyService.listCinema("nantes").then(res => {
expect(res.data.status).toBe('OK');
});
});
test('Status is 404', () => {
return enjoyService.listCinema("X Æ A-XII").catch(err => {
expect(err.name).toBe("Error");
});
});
});
});

而下面使用的CCD_ 2

const axios = require('axios'),
googleBaseURL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=";
function listCinema(city) {
return axios.get(googleBaseURL + city + '&type=cinema&key=' + process.env.GOOGLE_API)
}

我发现了类似的GitHub问题。使用JESTExpressJS,它可以帮助其他有同样问题的人

类似的问题表明,我们必须添加到jest.config.js

{
// ...
testEnvironment: 'node'
// ...
}

在我的情况下,我将下面的代码添加到我的package.json中,就像一样

"jest": {
"testEnvironment": "node"
},

很高兴知道如果您想像我一样从package.json添加配置

如果您想使用您的package.json来存储Jest的配置"玩笑;密钥应该在顶层使用,这样Jest就会知道如何查找您的设置:

{
"name": "my-project",
"jest": {
"verbose": true
}
}

我已经能够通过添加以下验证片段来解决这个问题:

import axios from 'axios'
if(typeof process != 'undefined'){
axios.defaults.adapter = require('axios/lib/adapters/http');
}
/.../

更多本地解决方案

您可以通过在测试文件顶部添加一个文档块来更改特定测试的测试环境甚至单个环境选项,而不是全局更改测试环境以使一个测试工作。

有关更多信息,请参阅文档:https://jestjs.io/docs/configuration#testenvironmentoptions-目标

/**
* @jest-environment-options {"url": "http://other-than-localhost"}
*/

最新更新