Jest createSpyObj

前端 未结 3 1155
青春惊慌失措
青春惊慌失措 2021-01-02 06:03

With Chai, you can create a spy object as follows:

chai.spy.object([ \'push\', \'pop\' ]);

With jasmine, you can use:

jasmi         


        
3条回答
  •  借酒劲吻你
    2021-01-02 06:34

    David's answer helped to get me on the right track. I modified it to work with ionic-mocks (https://github.com/stonelasley/ionic-mocks) in my Ionic3/Angular4 project.

    In my test "helper" class, I have this:

    export function  createSpyObj (baseName: string, methodNames: string[]): { [key: string]: jasmine.Spy } {
      const obj: any = {}
      for (let i: number = 0; i < methodNames.length; i++) {
        obj[methodNames[i]] = jasmine.createSpy(baseName, () => {})
      }
      return obj
    }
    

    Then I'm able to use it as such in my test/spec file. I inject the provider in question as:

    { provide: AlertController, useFactory: () => AlertControllerMock.instance() },
    

    And until ionic-mocks is compatible with Jest, I have to copy over the mocks I want (which use createSpyObj):

    class AlertMock {
      public static instance (): any {
        const instance: any = createSpyObj('Alert', ['present', 'dismiss'])
        instance.present.and.returnValue(Promise.resolve())
        instance.dismiss.and.returnValue(Promise.resolve())
    
        return instance
      }
    }
    
    class AlertControllerMock {
      public static instance (alertMock?: AlertMock): any {
    
        const instance: any = createSpyObj('AlertController', ['create'])
        instance.create.and.returnValue(alertMock || AlertMock.instance())
    
        return instance
      }
    }
    

提交回复
热议问题