const Datastore = require('@google-cloud/datastore');
const datastore = Datastore();
function listTasks(res) {
const query = datastore.createQuery('Test');
datastore.runQuery(query)
.then((results) => {
const tasks = results[0];
tasks.forEach((task) => {
const taskKey = task[datastore.KEY];
console.log(taskKey.id, task);
});
res.send(tasks);
})
.catch((err) => {
console.error('ERROR:', err);
});
}
I want to unittest the above code, but I do not know how to mock/stub the google cloud datastore object/methods. For example, I want to mock/stub datastore.createQuery('Test'), but do not know how.
So I just came across the issue myself and here's how I resolved it.
Say your directory looks like the following:
And your
service.js
file is using GCP datastore i.e.What you can do is create a
__mocks__
directory adjacent to thenode_modules
directory.Where the datastore.js should have the following at the bare minimum:
Then reference the
datastore.js
file in yourpackage.json
by using themoduleNameMapper
property in the Jest configuration object.<rootDir>
is equivalent to the directory where your package.json file resides.Hope that helps!