Here is the unit test solution:
index.js
:
exports.listFiles = async (req, res) => {
const bucketName = req.body.bucket || req.query.bucket;
const { Storage } = require("@google-cloud/storage");
const storage = new Storage();
const [files] = await storage.bucket(bucketName).getFiles();
const result = [];
files.forEach((file) => {
result.push(file.name);
});
res.status(200).send(result);
};
index.spec.js
:
const sinon = require("sinon");
const { Storage } = require("@google-cloud/storage");
const { listFiles } = require(".");
describe("listFiles", () => {
afterEach(() => {
sinon.restore();
});
it("should pass", async () => {
const mFiles = [{ name: "sinon" }, { name: "mocha" }, { name: "chai" }];
const getFilesStub = sinon.stub().resolves([mFiles]);
const bucketStub = sinon.stub(Storage.prototype, "bucket").callsFake(() => ({ getFiles: getFilesStub }));
const mReq = { body: { bucket: "xxx-dev" }, query: { bucket: "xxx-release" } };
const mRes = { status: sinon.stub().returnsThis(), send: sinon.stub() };
await listFiles(mReq, mRes);
sinon.assert.calledWith(bucketStub, "xxx-dev");
sinon.assert.calledOnce(getFilesStub);
sinon.assert.calledWith(mRes.status, 200);
sinon.assert.calledWith(mRes.send, ["sinon", "mocha", "chai"]);
});
});
Unit test result with coverage report:
listFiles
✓ should pass
1 passing (12ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 50 | 100 | 100 | |
index.js | 100 | 50 | 100 | 100 | 2 |
index.spec.js | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59283121