如何在嵌套开玩笑的模拟功能中检查方法是否被调用



我有一个模拟服务,例如

  const firebaseService = jest.fn(() => ({
    initializeApp: jest.fn(() => { /*do nothing*/}),
  }))

在我的测试中,如果调用了initializeApp,我想进行expect。我该如何检查?

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

您可以将内间谍定义为变量。

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对象,该对象将模拟所有方法。您可以期望每种方法中的每一种。

最新更新