【发布时间】:2020-02-04 12:41:10
【问题描述】:
在向服务添加一些订阅后,我正在尝试修复单元测试(我对 Jasmine 不是特别熟悉)。我收到一个错误,说它们是未定义的。我不确定如何正确包含订阅。
我的组件(还有更多内容,但为了清楚起见,我已经缩短了):
export class AppComponent implements OnInit, AfterViewInit {
isSignedIn = false;
isLoggedIn = false;
signedInSubscription: Subscription;
loggedInSubscription: Subscription;
constructor(
private authenticationService: AuthenticationService,
private router: Router,
private http403Tester: Http403TestService,
) {
this.isLoggedIn = authenticationService.isLoggedIn;
this.isSignedIn = authenticationService.isSignedIn;
this.setEnvironment();
}
async ngOnInit() {
// line 69 below, this is where the error is
this.signedInSubscription = this.authenticationService.observableIsSignedIn.subscribe(item => {
this.isSignedIn = item;
});
this.loggedInSubscription = this.authenticationService.observableIsLoggedIn.subscribe(item => {
this.isLoggedIn = item;
});
}
}
服务:
export class AuthenticationService {
constructor() {
this.observableIsSignedIn = new BehaviorSubject<boolean>(this.isSignedIn);
this.observableIsLoggedIn = new BehaviorSubject<boolean>(this.isLoggedIn);
}
isSignedIn: boolean = null;
isLoggedIn: boolean = null;
observableIsSignedIn: any;
observableIsLoggedIn: any;
规格:
describe('AppComponent', () => {
let authenticationService: any;
let http403Tester: any;
let router: any;
let component: AppComponent;
beforeEach(() => {
authenticationService = {
isSignedIn: jasmine.createSpy(),
isLoggedIn: jasmine.createSpy(),
observableIsSignedIn: jasmine.createSpy(),
observableIsLoggedIn: jasmine.createSpy(),
};
router = { navigateByUrl: jasmine.createSpy() };
http403Tester = { isAuthenticated: jasmine.createSpy() };
component = new AppComponent(authenticationService, router, http403Tester);
});
describe('ngOnInit()', () => {
it('should navigate to /unauthorised when a 403 status code is returned', async () => {
// Arrange
http403Tester.isAuthenticated.and.returnValue(false);
// Act
await component.ngOnInit();
// Assert
expect(router.navigateByUrl).toHaveBeenCalledWith('/unauthorised');
});
还有错误:
TypeError: Cannot read property 'subscribe' of undefined
at AppComponent.<anonymous> (src/app/app.component.ts:69:83)
所以我很确定 createSpy() 是模拟订阅的不正确方法:
observableIsSignedIn: jasmine.createSpy()
但我不知道如何继续或搜索什么。有什么想法吗?
【问题讨论】:
-
如果
http403Tester上的isAuthenticated是BehaviourSubject,您必须按照Ramesh Rejendran 的建议进行操作,并输入BehviorSubject而不是jasmine.createSpy()。你能准确地显示line 69吗? -
在第一个sn-p中用注释表示。
标签: angular typescript jasmine