开玩笑的模拟无法迭代异步交互

问题描述 投票:0回答:1

我在我的 Nodejs 应用程序中使用

google-cloud/compute
库来获取我帐户中永久磁盘的详细信息。

const { DisksClient } = require("@google-cloud/compute").v1;

module.exports = () => {
    const getAllDisks = async (credential, project) => {

        const allDisks = [];

        const client = computeClient({ credentials });
        const aggregatedList = client.aggregatedListAsync({ project });

        for await (const [zone, disksScoped] of aggregatedList){
            allDisks.push([zone, disksScoped]);
        }

        return { allDisks };
    }

    return { getAllDisks };
};


到目前为止一切顺利。

我正在尝试为此进行单元测试,并且遇到了一个模拟

aggregatedListAsync
方法的问题。

const { DisksClient } = require("@google-cloud/compute").v1;
jest.mock("@google-cloud/compute");
const { getAllDisks } = require("../src/getAllDisks")();

const mockDisks = [
    [
        "regions/us-central1",
        {
            disks: [],
            ...
        }
    ]
]

const mockAsyncIterator = {
    [Symbol.asyncIterator]: function(){
        return mockDisks;
    }
}

describe("getAllDisks unit test", () => {
    describe("Given a successful call", () => {
        beforeEach(() => {
            DisksClient.prototype.aggregatedListAsync.mockResolvedValue(mockAsyncIterator);
        });
        it("Should return disks", async () => {
            const result = await getAllDisks("creds", "projectid");
            const { allDisks } = result;
            expect(...)
        })
    });
});

测试时抛出的错误表明

aggregatedList is not async iterable

aggregatedListAsync
的类型定义如下:

aggregatedListAsync(request?: protos.google.cloud.compute.v1.IAggregatedListDisksRequest, options?: CallOptions): AsyncIterable<[string, protos.google.cloud.compute.v1.IDisksScopedList]>;

因此 for-await-of 确实成功检索了我的项目中的持久磁盘资源。

我注意到使用

.mockResolvedValue
实际上返回了一个 promise 解析为异步迭代器。 但是,当更改为
.mockReturnValue
时,错误消息现在为
".for is not iterable"

我认为问题是由于我的模拟格式造成的,但是..仍然不确定,因为我无法解决它。

node.js jestjs iterator
1个回答
0
投票

跑步笑话和苹果硅似乎不兼容。

解决方法是在 64 位 shell 中运行测试。

arch -86_64 zsh

npx jest ...
© www.soinside.com 2019 - 2024. All rights reserved.