我在Google的Cloud Build上运行集成测试时遇到了问题。
单元测试运行良好,但是向外部API (使用Axios)发出请求的集成测试在Cloud Build: connect ECONNREFUSED 127.0.0.1:80中显示此错误。
这是一个使用创建React App构建的React应用程序。下面是cloudbuild.json:
{
"steps": [
{
"name": "gcr.io/cloud-builders/npm",
"entrypoint": "npm",
"args": [
"install"
],
},
{
"name": "gcr.io/cloud-builders/npm",
"entrypoint": "npm",
"args": [
"run", "build"
],
},
{
"name": "gcr.io/cloud-builders/npm",
"entrypoint": "npm",
"args": [
"test"
],
"env": [
"CI=true",
],
}
]
}下面是一个错误示例:
Step #1: src/reducers/readings › should update state appropriately when starting a fetch readings request
Step #1:
Step #1: connect ECONNREFUSED 127.0.0.1:80任何帮助都将不胜感激!
--
跟进:
我最终用这个来追踪这个问题。外部API url是在.env文件中定义的。由于Cloudbuild无法访问这些变量,因此Axios调用默认为127.0.0.1 (localhost),这将失败。
通过加密环境文件,将其存储为Cloud KMS密钥,并授予云构建器对其的访问权限,修复了该问题。
# Decrypt env variables
- name: gcr.io/cloud-builders/gcloud
args:
- kms
- decrypt
- --ciphertext-file=.env.enc
- --plaintext-file=.env
- --location=global
- --keyring=[KEYRING]
- --key=[KEY]感谢@ffd03e的指针。
发布于 2019-04-12 03:36:50
外部API是在Cloud Build中运行还是在其他地方运行?看一看测试会很有帮助。另外,CI=true是否会被选中,或者测试是否会挂起在监视模式下?(https://facebook.github.io/create-react-app/docs/running-tests#linux-macos-bash)
您的测试似乎正在尝试连接到localhost,但由于localhost:80上没有运行任何东西而失败。Cloud Build应该能够连接到外部API。下面是一个示例:
到src/App.test.js的
mkdir gcb-connect-test && cd gcb-connect-testnpx create-react-app .touch cloudbuild.yaml// This test fails
it('connects with localhost', async () => {
const response = await axios.get('localhost');
console.log('axios localhost response: ' + response.data);
expect(response).toBeTruthy();
});
// This test passes
it('connect with external source', async () => {
const response = await axios.get('https://jsonplaceholder.typicode.com/users/10');
console.log('axios external response: ' + response.data.name);
expect(response.data.name).toBeTruthy();
});cloudbuild.yaml (我更喜欢yaml,因为您可以添加注释(-:)steps:
# npm install
- name: 'gcr.io/cloud-builders/npm'
args: ['install']
# npm run build
- name: 'gcr.io/cloud-builders/npm'
args: ['run', 'build']
# bash -c | CI=true npm test
# syntax to add commands before npm (-:
- name: 'gcr.io/cloud-builders/npm'
entrypoint: 'bash'
args:
- '-c'
- |
CI=true npm testgcloud builds submit .如果这最终是一个比意外连接到本地主机更奇怪的问题,那么gcp slack上的#cloudbuild通道是一个很好的资源:slack sign up link
https://stackoverflow.com/questions/55576270
复制相似问题