#node.js #oauth-2.0 #oauth #mocha.js #integration-testing
Вопрос:
Я не могу понять, почему интеграционный тест не будет работать с приведенным ниже кодом. Код работает следующим образом; функция «makeOauthRequest» делает запрос к API Oauth для получения маркера доступа. Функция «createMeeting» получает маркер доступа и использует его для отправки запроса на публикацию в API масштабирования.
Если бы я вызвал функцию»createMeeting» внутри самого файла приложения с тем же вызовом, что и в тестовом файле (с помощью «createMeeting («Пожалуйста, работайте с API», «2021-04-26T19:20:00Z»)»), она работала бы и успешно выполняла запрос post. Однако, согласно приведенному ниже тестовому файлу, когда я делаю тот же вызов через Mocha, он выдает ошибку 400. Может кто-нибудь, пожалуйста, помочь мне понять, почему существует это несоответствие?
Я зарегистрировал переменные среды в файле теста, чтобы проверить, не было ли проблем с их пониманием тестом, но они кажутся нормальными.
// Test file
const funcs = require("../auto/autoNeg.js");
const assert = require("chai").assert;
require("dotenv").config({ path : '/Users/frederickgodsell/codefiles/mokapot/auto/.env'});
describe('Simple integration', function() {
it('Integration works', async function() {
const resp = await createMeeting("Please Work API", "2021-04-26T19:20:00Z");
console.log(resp)
});
});
// Fails with 'Error: Request failed with status code 400'
// App file
const axios = require("axios").defau<
require("dotenv").config();
const fs = require("fs");
const jsonString = fs.readFileSync(`/Users/frederickgodsell/codefiles/mokapot/refresh.json`);
const fileData = JSON.parse(jsonString);
const refTok = fileData.refresh_token;
const oathOptions = {
headers: {
Authorization:
"Basic "
Buffer.from(process.env.ID ":" process.env.SECRET).toString("base64"),
},
params: {
grant_type: "refresh_token",
refresh_token: refTok,
},
};
makeOauthRequest = async () => {
try {
const oauthPostRequest = await axios.post(
"https://zoom.us/oauth/token",
{},
oathOptions
);
let accessPlusRefresh = JSON.stringify(
await oauthPostRequest.data,
null,
2
);
fs.writeFile(`/Users/frederickgodsell/codefiles/mokapot/refresh.json`, accessPlusRefresh, (error) => {
if (error) {
console.log("Error writing file", error);
} else {
console.log("JSON file sucessfully updated");
}
});
// console.log(oauthPostRequest.data)
return oauthPostRequest.data;
} catch (error) {
console.log(error);
}
};
createMeeting = async (topic, startTime) => {
let meetingBody = {
topic: topic,
start_time: startTime,
};
let response = await makeOauthRequest();
let accessToken = await response.access_token;
const meetingOptions = {
headers: {
authorization: `Bearer ${await accessToken}`,
"Content-Type": "application/json",
},
};
if (!topic || !startTime) {
console.log('Please provide both a topic and a start time')
return 'Please provide both a topic and a start time'
}
try {
let meetingResponse = await axios.post(
`${process.env.API_URL}`,
meetingBody,
meetingOptions
);
console.log(`Meetin booked. UUID : ${meetingResponse.data.uuid}`);
return meetingResponse;
} catch (err) {
console.log(err.response.data);
}
};
module.exports.createMeeting = createMeeting;
module.exports.makeOauthRequest = makeOauthRequest;
module.exports.oathOptions = oathOptions;
module.exports.refTok = refTok;
// package.json file for good measure
{
"name": "mokapot",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha -r dotenv/config"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.21.1",
"chai": "^4.3.4",
"dotenv": "^8.2.0",
"mocha": "^8.3.2",
"nock": "^13.0.11",
"sinon": "^9.2.4",
"supertest": "^6.1.3"
}
}