任何人都可以在下面的一个示例测试方案中帮助我写信。
[storage
是库(google Cloud),最后在代码行下面将返回包含文件名和日期的数组。
function abc(){
const files = [];
files = await storage.bucket(bucketName).getFiles();
return files;
}
这里是单元测试解决方案:
index.ts
:
import { Storage } from "@google-cloud/storage";
const storage = new Storage();
export async function abc() {
const bucketName = "xxx-dev";
const files = await storage.bucket(bucketName).getFiles();
return files;
}
index.spec.ts
:
import { abc } from "./";
import { Storage } from "@google-cloud/storage";
import sinon from "sinon";
import { expect } from "chai";
describe("abc", () => {
afterEach(() => {
sinon.restore();
});
it("should pass", async () => {
const getFilesStub = sinon.stub().resolves(["file1", "file2"]);
const bucketStub = sinon.stub(Storage.prototype, "bucket").callsFake(() => {
return { getFiles: getFilesStub } as any;
});
const actual = await abc();
expect(actual).to.be.deep.eq(["file1", "file2"]);
sinon.assert.calledWith(bucketStub, "xxx-dev");
sinon.assert.calledOnce(getFilesStub);
});
});
单元测试结果覆盖率100%:
abc
✓ should pass
1 passing (39ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.spec.ts | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
软件包版本:
"@google-cloud/storage": "^4.1.3",
"sinon": "^7.5.0",
"mocha": "^6.2.2",
"chai": "^4.2.0",
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59373281