I am working on NodeJS test automation project. My goal is to get data from Mongo DB and use it in the tests. I successfully query the data from the DB, but so far I've failed to transfer the values to the test.
My Mongo DB halper (mongodbHelper.js):
var MongoClient = require('mongodb').MongoClient;
var url = "myurl";
var data;
const getTestData = async function(){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("my_test_collection").findOne({"testId": "test_01"}, function(err, result) {
if (err) throw err;
db.close();
data= result;
console.log(data); // This print prints correct data
return result;
});
});
}
module.exports =
{
getTestData
}
The print inside the handler prints retrieved data correctly. Now I need to use it in the test suite below. I want to initiate the testData variable in Before method and use it in tests. If I do it as below, the print in the test prints undefined. It prints it before the correct print in the helper. So I assume it is a synchronisation problem.
const mongodb = require('./mongodbHelper');
var testData;
describe('Playwright with Mocha Demo', function() {
before('name', async function() {
testData = await mongodb.getTestData();
console.log(testData); // Here it prints 'undefined'
});
....
Please advise how I can pass the data from the handler to the testData variable in the test correctly.
You aren't returning anything from your async function getTestData
.
The Mongo call is asynchronous but you're using a callback function. You could pass a callback function to getTestData
and call it with the data (where you're doing the console log). However, the Mongo calls return Promises, so you could just do something like this:
const getTestData = async function() {
const db = await MongoClient.connect(url);
const dbo = db.db("mydb");
const result = await dbo.collection("my_test_collection").findOne({"testId": "test_01"});
db.close();
return result;
});
Then in your test you can retrieve the data with:
testData = await mongodb.getTestData();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.