gpt4 book ai didi

javascript - 无法模拟模块中的函数

转载 作者:行者123 更新时间:2023-11-30 19:11:12 25 4
gpt4 key购买 nike

我正在尝试为模块创建一个简单的测试。我在一个模块中得到了一些 firestore 触发器(请参阅下面的模块文件)。在 onDelete 触发器中,我只想测试是否调用了 deleteColletion。为此,我只需要模拟 deleteCollection 函数。在我的测试中(请参阅测试文件中的 onDelete 还应删除子集合路径和下载)我模拟了 deleteCollection 函数并调用 firestore 触发器并检查是否 deleteCollection 被调用。这是我从测试中得到的失败响应:

Error: expect(jest.fn()).toBeCalled()

Expected number of calls: >= 1
Received number of calls: 0

jest 似乎与我模拟的函数不匹配。我做错了什么?

注意!我现在认为这个测试本身并不是一个好的测试;)

测试文件

const functions = require('firebase-functions-test');
const admin = require('firebase-admin');
const triggers = require("../../data/protocol/triggers");
const {createEvent} = require("../test_utilities");
const testEnv = functions();


const mockUpdate = jest.fn();
mockUpdate.mockReturnValue(true);

jest.mock("firebase-admin", () => ({
initializeApp: jest.fn(),
firestore: () => ({
batch: jest.fn(() => ({commit: jest.fn()})),
collection: () => (
{
doc: () => ({update: mockUpdate}),
orderBy: () => ({
limit: jest.fn(() => ({
get: jest.fn(() => ({
size: 0,
docs: {
forEach: jest.fn(),
}
}))
}))
})
}
)
}),
})
);

jest.mock('../../data/protocol/triggers', () => ({
...(jest.requireActual('../../data/protocol/triggers')),
deleteCollection: jest.fn(() => [])
})
);


describe("Protocol trigger", () => {
let adminStub, triggersStub, api;
const context = {
params: {
protocolId: 0,
}
};

beforeAll(() => {
adminStub = jest.spyOn(admin, "initializeApp");
//triggersStub = jest.spyOn(triggers, 'deleteCollection');
api = require("../../index");
});

beforeEach(() => jest.clearAllMocks());

afterAll(() => {
adminStub.mockRestore();
//triggersStub.mockRestore();
testEnv.cleanup();
});


...

it('`onDelete` should also delete the sub-collections `trails` and `downloads`', async () =>
{
const onDeleteProtocol = testEnv.wrap(api.onDeleteProtocol);
const event = {id: 0};

await onDeleteProtocol(event, {});

expect(triggers.deleteCollection).toBeCalled();
expect(onDeleteProtocol(event, {})).toBe([]);


});
});

模块

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {lastModifiedNeedsUpdate} = require("../utilities/event");

function deleteCollection(db, collectionPath, batchSize) {
return deleteQueryBatch(db, db.collection(collectionPath).orderBy('__name__').limit(batchSize), batchSize, []);
}

...

const deleteProtocol = () => functions.firestore
.document('protocols/{protocolId}')
.onDelete((event, context) => {
return deleteCollection(admin.firestore(), `protocols/${event.id}/trails`, 1);
});


module.exports = {
deleteProtocol,
createProtocol,
updateProtocol,
deleteCollection,
};

-- 弗罗德

最佳答案

我通过将辅助函数(deleteCollectiondeleteQueryBatch)移动到它自己的模块中并模拟该模块来解决这个问题。

--弗罗德

关于javascript - 无法模拟模块中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58458242/

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