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.
There is not much you can do. Either mock whole datastore by yourself, use local emulator, or mock only methods that you need for every test case.
The first approach might be effortable and complex, but will guarantee the best possible response time and tests speed.
The second approach will also work, but in my practice this working not faster than real datastore in project. I mean, local emulator response times in my machine where about 30 ms - 400 ms, that almost the same as using remote datastore instance. Don't know why, maybe I did something wrong. You can try at least.
The third approach, will be something in between of the two first, but you'll start to test implementation instead of behavior, and such test become useless. But, this is only my opinion regarding such approach.
There is one more approach, the fourth would be to decompose such method, so they don't have database communication code, and only algorithmic part. Test such code, and not the one that call db methods.