Brought to you by the Mob Squad
Writing integration tests for some route handlers in the purchase system.
module.exports = routeConfig =>
(req, res, next) =>
database.getInventoryBatch(res.locals.pool, req.params.id)
.then(inventoryBatch =>
res.send(Object.assign({id: Number(req.params.id)}, {inventoryBatch})))
.catch(error => {
const moovelError = MoovelError.from(error);
routeConfig.logger.warn(moovelError);
res.status(moovelError.status).send(moovelError);
});
module.exports = (pool, productId) =>
pool.query(getInventoryBatchSQL, productId)
.then(_.first)
.tap(inventoryBatch => {
if (!inventoryBatch) {
throw MoovelError.create(`Inventory batch record for product id ${productId} not found`, {
status: 'RESOURCE_NOT_FOUND',
code: 'error-not-found'
});
}
});
The handler for the route
The boundary with the database.
it('retreives product information by id', function() {
return getProduct(req, res, next).then(result => {
expect(res.locals.pool.query).to.have.been.calledWith(queryString, 1);
expect(res.send).to.have.been.calledWith(expectedResult);
expect(res.send).to.have.been.calledOnce;
});
});
it('responds with an error if no product information is available', function() {
res.locals.pool.query = sinon.stub().resolves([]);
return getProduct(req, res, next).then(result => {
expect(res.status).to.have.been.calledWith(420);
expect(res.send).to.have.been.calledWith(noProductError);
});
});
it('responds with an error when the database encounters a problem', function() {
res.locals.pool.query = sinon.stub().rejects(new Error('problems'));
return getProduct(req, res, next).then(result => {
expect(res.status).to.have.been.calledWith(500);
expect(res.send).to.have.been.calledWith(dbError);
});
});
This is what I came up with:
Questions?