5

我有一个像下面这样的模拟服务

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

1 回答 1

5

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

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所有方法都被模拟的对象。您可以期待这些方法中的每一种。

于 2019-07-31T19:57:31.720 回答