简体   繁体   English

如何检查是否在嵌套的Jest模拟函数中调用了方法

[英]How to check if a method is called in nested jest mock functions

I have a mock service like below 我有一个如下的模拟服务

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

in my test I want to expect if initializeApp has been called. 在我的测试中,我想expect是否调用了initializeApp How can I check that? 我该如何检查?

it('should be called', () => {
   expect(???).toHaveBeenCalledTimes(1);
});

Update : Real scenario 更新:真实场景

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

and I want to check below 我想在下面检查

 expect(firebaseService.firestore.collection).toHaveBeenCalled();
 expect(firebaseService.firestore.collection.where).toHaveBeenCalled();    
 expect(firebaseService.firestore.collection.where).toHaveBeenCalledWith(`assignedNumbers.123`, '==', true);

You can define the inner spy as a variable. 您可以将内部间谍定义为变量。

const initializeAppSpy = jest.fn(() => { /*do nothing*/});

const firebaseService = jest.fn(() => ({
    initializeApp: initializeAppSpy,
}))

Then you can use the reference in order to expect on it: 然后,您可以使用该引用,以期对其expect

it('should be called', () => {
   expect(initializeAppSpy).toHaveBeenCalledTimes(1);
});

EDIT You can create a mock to the entire service 编辑您可以为整个服务创建一个模拟

const firebaseMock = {
   method1: 'returnValue1',
   method2: 'returnValue2'
}

Object.keys(firebaseMock).forEach(key => {
   firebaseMock[key] = jest.fn().mockReturnValue(firebaseMock[key]);
});

const firebaseService = jest.fn(() => firebaseMock);

now, you will have a firebaseMock object that all the methods are mocked. 现在,您将拥有一个firebaseMock所有方法的firebaseMock对象。 you can expect on each one of those methods. 您可以期望其中的每一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM