gpt4 book ai didi

google-cloud-platform - 如何使用 sinon 、 mocha chai 模拟以下代码的响应

转载 作者:行者123 更新时间:2023-12-02 00:09:58 24 4
gpt4 key购买 nike

谁能帮我写一个示例测试场景?

storage 是一个库(谷歌云),最后一行代码将返回一个由文件名和日期组成的数组。

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;
}

export async function xyz(res) {
const bucketName = "xxx-dev";
return storage
.bucket(bucketName)
.file(res.fileName)
.createReadStream();
}

index.spec.ts:

import { abc, xyz } from "./";
import { Storage } from "@google-cloud/storage";
import sinon from "sinon";
import { expect } from "chai";

describe("59373281", () => {
afterEach(() => {
sinon.restore();
});
it("abc 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);
});

it("xyz should pass", async () => {
const fileStub = sinon.stub().returnsThis();
const createReadStreamStub = sinon.stub();
const bucketStub = sinon.stub(Storage.prototype, "bucket").callsFake(() => {
return {
file: fileStub,
createReadStream: createReadStreamStub,
} as any;
});
const mRes = { fileName: "jestjs.pdf" };
await xyz(mRes);
sinon.assert.calledWith(bucketStub, "xxx-dev");
sinon.assert.calledWith(fileStub, "jestjs.pdf");
sinon.assert.calledOnce(createReadStreamStub);
});
});

100% 覆盖率的单元测试结果:

  59373281
✓ abc should pass
✓ xyz should pass


2 passing (46ms)

---------------|----------|----------|----------|----------|-------------------|
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

关于google-cloud-platform - 如何使用 sinon 、 mocha chai 模拟以下代码的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59373281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com