我有如下的模拟服务
const firebaseService = jest.fn(() => ({
initializeApp: jest.fn(() => { /*do nothing*/}),
}))
在我的测试中,我想expect
被调用initializeApp
。
我该如何检查?
it('should be called', () => {
expect(???).toHaveBeenCalledTimes(1);
});
const collection = jest.fn(() => {
return {
doc: jest.fn(() => {
return {
collection: collection,
update: jest.fn(() => Promise.resolve(true)),
onSnapshot: jest.fn(() => Promise.resolve(true)),
get: jest.fn(() => Promise.resolve(true))
}
}),
where: jest.fn(() => {
return {
get: jest.fn(() => Promise.resolve(true)),
onSnapshot: jest.fn(() => Promise.resolve(true)),
limit: jest.fn(() => {
return {
onSnapshot: jest.fn(() => Promise.resolve(true)),
get: jest.fn(() => Promise.resolve(true)),
}
}),
}
}),
limit: jest.fn(() => {
return {
onSnapshot: jest.fn(() => Promise.resolve(true)),
get: jest.fn(() => Promise.resolve(true)),
}
})
}
});
const Firestore = {
collection: collection
}
firebaseService = {
initializeApp() {
// do nothing
},
firestore: Firestore
};
我想在下面检查
expect(firebaseService.firestore.collection).toHaveBeenCalled();
expect(firebaseService.firestore.collection.where).toHaveBeenCalled();
expect(firebaseService.firestore.collection.where).toHaveBeenCalledWith(`assignedNumbers.123`, '==', true);
答案 0 :(得分:2)
您可以将内部间谍定义为变量。
const initializeAppSpy = jest.fn(() => { /*do nothing*/});
const firebaseService = jest.fn(() => ({
initializeApp: initializeAppSpy,
}))
然后,您可以使用引用来在其上expect
:
it('should be called', () => {
expect(initializeAppSpy).toHaveBeenCalledTimes(1);
});
编辑 您可以为整个服务创建一个模拟
const firebaseMock = {
method1: 'returnValue1',
method2: 'returnValue2'
}
Object.keys(firebaseMock).forEach(key => {
firebaseMock[key] = jest.fn().mockReturnValue(firebaseMock[key]);
});
const firebaseService = jest.fn(() => firebaseMock);
现在,您将拥有一个模拟所有方法的firebaseMock
对象。
您可以期望其中的每一种方法。