Angular 6测试-茉莉花-模拟链式承诺

时间:2018-07-21 07:13:04

标签: angular unit-testing karma-jasmine jasmine2.0

我的服务中有一个要测试的方法register()。我的断言是,从注入的服务调用了另一个方法。让我们更深入地研究我的代码:

服务

export class OAuthRegistrationService {

  constructor(private afAuth: AngularFireAuth,
              private afs: AngularFirestore) {
  }

  public register(register: RegisterDataModel): Promise<void | string> {
    return this.afAuth.auth.createUserWithEmailAndPassword(register.email, register.password)
      .then(() => {
      const user = this.afAuth.auth.currentUser;
      this.setUser(user, register).then(() =>
        user.sendEmailVerification().then(() => 'Please verify your email').catch((err) => err));
    }).catch((err: FirebaseErrorModel) => err.message);
  }
}

现在在单元测试中,我想断言sendEmailVerification已被调用。现在,我需要正确模拟上面调用的pomis,以检查是否已调用此方法。

规格文件/单元测试

describe('OAuthRegistrationService', () => {
  let service: OAuthRegistrationService;
  // stubs
  const afAuthStub = {
    auth: {
      sendEmailVerification(): Promise<void> {
        return new Promise<void>(resolve => resolve());
      },
      createUserWithEmailAndPassword(): Promise<void> {
        return new Promise<void>(resolve => resolve());
      },
      currentUser: {
        uid: 'blub'
      }
    }
  };

  const afsStub = {
    doc(path: string) {
      return {
        set() {
          return path;
        }
      };
    }
  }

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        {provide: AngularFireAuth, useValue: afAuthStub},
        {provide: AngularFirestore, useValue: afsStub},
        OAuthRegistrationService
      ]
    });
    service = TestBed.get(OAuthRegistrationService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should send email verification', () => {
    const register: RegisterDataModel = new RegisterDataModel('username', 'abc@email.com', 'password', null, null);

    const mock = TestBed.get(AngularFireAuth);
    const spy = spyOn(afAuthStub.auth, 'sendEmailVerification').and.callThrough();
    spyOn(afAuthStub.auth, 'createUserWithEmailAndPassword').and.callThrough();
    mock.auth = afAuthStub.auth;

      service.register(register).then(() => {
        expect(spy).toHaveBeenCalled();
    });
  });
});

茉莉花and.callTrough允许我调用Promise .then()方法并转到测试方法的下一步。但是控制台以某种方式说:我的间谍从未被调用过。有人知道吗,我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

您的存根稍有不正确,sendEmailVerification()方法属于currentUser属性。

const afAuthStub = {
  auth: {
    createUserWithEmailAndPassword(): Promise<void> {
      return new Promise<void>(resolve => resolve());
    },
    currentUser: {
      uid: 'blub',
      sendEmailVerification(): Promise<void> {
        return new Promise<void>(resolve => resolve());
      },
    }
  }
};

...

const spy = spyOn(afAuthStub.auth.currentUser, 'sendEmailVerification')

这里是StackBlitz,测试通过。