问题
I am trying to run a sample test using Jest to verify if my Google Cloud Function is working fine or not but I am constantly getting following error.
Error: Command failed: gcloud beta functions call cf-1 --region europe-west1 --data '{"data":"eyJkYXRhIjoiMSJ9"}'
ERROR: (gcloud.beta.functions.call) Invalid value for [--data]: Is not a valid JSON: No JSON object could be decoded
I know that i can escape double quotes with backslash when running the command in windows terminal but how to do it in JavaScript.
test.js
const childProcess = require('child_process');
describe('Test CF', () => {
it('print outs the error message when received JSON is blank', done => {
const msg = { data: '1' };
const encodedMsg = Buffer.from(JSON.stringify(msg)).toString('base64');
const data = JSON.stringify({ data: encodedMsg });
const executeResultOutput = childProcess.execSync(`gcloud beta functions call cf-1 --region europe-west1 --data '${data}'`).toString();
const logs = childProcess
.execSync(
`gcloud functions logs read cf-1 --region europe-west1 --execution-id ${executionIdObj}`,
)
.toString();
expect(logs).toEqual(expect.stringContaining('Error..'));
});
});
回答1:
Try it twice:
data = {"data":"eyJkYXRhIjoiMSJ9"}
console.log(
JSON.stringify(JSON.stringify(data))
)
来源:https://stackoverflow.com/questions/57994072/escaping-double-quotes-in-windows-commands