Tap*_*pas 2 mocha.js sinon google-cloud-storage google-cloud-platform google-cloud-functions
谁能帮我编写一个示例测试场景?
storage
是一个库(谷歌云)最终在代码行下方将返回一个由文件名和日期组成的数组。
function abc(){
const files = [];
files = await storage.bucket(bucketName).getFiles();
return files;
}
Run Code Online (Sandbox Code Playgroud)
这是单元测试解决方案:
\n\nindex.ts
:
import { Storage } from "@google-cloud/storage";\nconst storage = new Storage();\n\nexport async function abc() {\n const bucketName = "xxx-dev";\n const files = await storage.bucket(bucketName).getFiles();\n return files;\n}\n\nexport async function xyz(res) {\n const bucketName = "xxx-dev";\n return storage\n .bucket(bucketName)\n .file(res.fileName)\n .createReadStream();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\nindex.spec.ts
:
import { abc, xyz } from "./";\nimport { Storage } from "@google-cloud/storage";\nimport sinon from "sinon";\nimport { expect } from "chai";\n\ndescribe("59373281", () => {\n afterEach(() => {\n sinon.restore();\n });\n it("abc should pass", async () => {\n const getFilesStub = sinon.stub().resolves(["file1", "file2"]);\n const bucketStub = sinon.stub(Storage.prototype, "bucket").callsFake(() => {\n return { getFiles: getFilesStub } as any;\n });\n const actual = await abc();\n expect(actual).to.be.deep.eq(["file1", "file2"]);\n sinon.assert.calledWith(bucketStub, "xxx-dev");\n sinon.assert.calledOnce(getFilesStub);\n });\n\n it("xyz should pass", async () => {\n const fileStub = sinon.stub().returnsThis();\n const createReadStreamStub = sinon.stub();\n const bucketStub = sinon.stub(Storage.prototype, "bucket").callsFake(() => {\n return {\n file: fileStub,\n createReadStream: createReadStreamStub,\n } as any;\n });\n const mRes = { fileName: "jestjs.pdf" };\n await xyz(mRes);\n sinon.assert.calledWith(bucketStub, "xxx-dev");\n sinon.assert.calledWith(fileStub, "jestjs.pdf");\n sinon.assert.calledOnce(createReadStreamStub);\n });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n100%覆盖率的单元测试结果:
\n\n 59373281\n \xe2\x9c\x93 abc should pass\n \xe2\x9c\x93 xyz should pass\n\n\n 2 passing (46ms)\n\n---------------|----------|----------|----------|----------|-------------------|\nFile | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |\n---------------|----------|----------|----------|----------|-------------------|\nAll files | 100 | 100 | 100 | 100 | |\n index.spec.ts | 100 | 100 | 100 | 100 | |\n index.ts | 100 | 100 | 100 | 100 | |\n---------------|----------|----------|----------|----------|-------------------|\n
Run Code Online (Sandbox Code Playgroud)\n\n软件包版本:
\n\n"@google-cloud/storage": "^4.1.3",\n"sinon": "^7.5.0",\n"mocha": "^6.2.2",\n"chai": "^4.2.0",\n
Run Code Online (Sandbox Code Playgroud)\n\n源代码: https: //github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59373281
\n 归档时间: |
|
查看次数: |
1066 次 |
最近记录: |