我正在使用弹珠为服务创建单元测试。经过测试的服务方法(我只留下了一个有问题的片段)
updatePayment(payment: Partial<Payment>, familyId: string): Observable<void> {
return this.authenticationService.getUser()
}
我已经创建了一个服务模拟
function getAuthenticationServiceSpy() {
...
// tslint:disable-next-line: max-line-length
const authenticationServiceSpy: jasmine.SpyObj<AuthenticationService> = jasmine.createSpyObj(
'AuthenticationService', ['getUser']
);
authenticationServiceSpy.getUser.and.returnValue(hot('--a', { a: user }));
return authenticationServiceSpy;
}
export interface IAuthenticationServiceMock {
getService: () => jasmine.SpyObj<AuthenticationService>;
user: User;
}
// tslint:disable-next-line: max-line-length
export const AuthenticationServiceMock: () => IAuthenticationServiceMock = () => ({
getService: getAuthenticationServiceSpy,
user
});
我用它来规范服务
describe('PaymentsService', () => {
let service: PaymentsService;
let authenticationServiceSpy: jasmine.SpyObj<AuthenticationService>;
let authenticationServiceMock: IAuthenticationServiceMock;
const scheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
beforeEach(() => {
authenticationServiceMock = AuthenticationServiceMock();
authenticationServiceSpy = authenticationServiceMock.getService();
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
{ provide: AuthenticationService, useValue: authenticationServiceSpy }
]
});
service = TestBed.get(PaymentsService);
httpTestingController = TestBed.get(HttpTestingController);
});
it('should do the thing', () => {
const mockedFamilyId = 'familyId-1';
const updatedPayment = {};
service.updatePayment(updatedPayment, mockedFamilyId)
.subscribe(payment => {
expect(1).toBe(2); // should fail
});
}
);
});
这个测试成功的问题,不应该是这样的。据我了解 authenticationServiceSpy.getUser()
没有发出值,但我不明白为什么。如果我改变
authenticationServiceSpy.getUser.and.returnValue(hot('--a', { a: user }));
到
authenticationServiceSpy.getUser.and.callFake(() => hot('--a', { a: user }));