使用Firebase身份验证的单元测试角度服务?

时间:2019-03-19 06:46:01

标签: angular firebase unit-testing jasmine firebase-authentication

我在angular上设置了简单的身份验证服务,该服务会返回Promise:

import * as firebase from 'firebase/app';

@Injectable({
    providedIn: 'root'
})

export class AuthService {

  doLogin(val:{email:string, password:string}) {
  return new Promise<any>((resolve, reject) => {
    firebase
      .auth()
      .signInWithEmailAndPassword(val.email, val.password)
      .then(
        res => resolve(res),
        err => reject(err)
      );
    });
  }

}

如何正确执行服务上的单元测试? 通过提供真实的用户凭证(这不是一件好事,因为我要将代码推送到github)并使用凭证直接调用doLogin方法,目前我使用茉莉花进行单元测试的方法。 >

describe('AuthService', () => {
let service: AuthService;
const userCreds = {
    email: 'somerealemail@somedomain.com',
    password: 'somerealpassword'
};

beforeEach(() => TestBed.configureTestingModule({
    imports: [FirebaseModule],
    providers: [AuthService]
}));

beforeEach(() => {
    service = TestBed.get(AuthService);
});

it('should logged in', async((done) => {
    service.doLogin(userCreds).then(
        res => {
            expect(res).toBeTruthy();
        }
    )
}));

很抱歉,如果代码混乱,我在角度和茉莉花方面都是全新的,任何建议或想法都将不胜感激, 谢谢

1 个答案:

答案 0 :(得分:1)

I would strongly suggest you refactor your code to use dependency injection. See the docs here.

You would then inject Firebase as an external dependency, which will make it much easier to mock and therefore much easier to test. See examples on how to do this with Firebase in The official Angular library for Firebase

Once you have done this, then you can test it in a fairly straightforward way. Here is an example in Stackblitz of testing a firebase service.