在使用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");
});
});
});
});而enjoy.service使用的是下面
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)
}发布于 2021-05-16 10:38:05
我找到了一个相似GitHub问题。使用JEST和ExpressJS可以帮助其他人解决同样的问题。
类似的问题是,我们必须增加我们的jest.config.js
{
// ...
testEnvironment: 'node'
// ...
}在我的例子中,我将下面的代码添加到我的package.json中,如下所示
"jest": {
"testEnvironment": "node"
},很高兴知道,如果你想像我一样从你的package.json中添加配置
如果您想使用您的package.json来存储Jest的配置,则应该在顶层使用"jest“键,这样Jest将知道如何找到您的设置: {“名称”:“我的项目”,“开玩笑”:{“详细”:真}
发布于 2021-09-03 21:30:47
通过添加以下验证片段,我能够解决这个问题:
import axios from 'axios'
if(typeof process != 'undefined'){
axios.defaults.adapter = require('axios/lib/adapters/http');
}
/.../发布于 2022-07-19 11:51:35
更多的局部解决方案
您可以通过在测试文件的顶部添加一个docblock来更改测试环境,甚至可以更改该特定测试的单个环境选项,而不是在全局范围内更改测试环境以使一个测试工作正常。
有关更多信息,请参见文档:https://jestjs.io/docs/configuration#testenvironmentoptions-object
/**
* @jest-environment-options {"url": "http://other-than-localhost"}
*/
https://stackoverflow.com/questions/67555622
复制相似问题