我无法让集成测试在Google的Cloud Build上运行。
单元测试运行良好,但是对外部API进行请求(使用Axios)的集成测试在Cloud Build中显示此错误:connect ECONNREFUSED 127.0.0.1:80。
这是使用Create 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网址是在.env文件中定义的。由于Cloudbuild无法访问这些变量,因此Axios调用默认为127.0.0.1(localhost),但失败。
此问题已通过加密env文件,将其存储为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指针。
答案 0 :(得分:0)
外部API是否正在Cloud Build或其他地方运行?查看测试会有所帮助。此外,是否会接受CI = true或测试是否在监视模式下挂起? (https://facebook.github.io/create-react-app/docs/running-tests#linux-macos-bash)
您的测试似乎正在尝试连接到localhost
,该测试失败了,因为localhost:80
上没有任何内容。 Cloud Build应该能够连接到外部API。这是一个示例:
mkdir gcb-connect-test && cd gcb-connect-test
npx create-react-app .
touch cloudbuild.yaml
src/App.test.js
// 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 test
gcloud builds submit .
如果这最终成为一个奇怪的问题,而不仅仅是偶然连接到本地主机,那么gcp松弛上的#cloudbuild通道是一个很好的资源:slack sign up link