我正在为组件编写测试以检查其真实性。组件的ngOnInit()从本地存储中检索数据,并具有设置一些数据的方法
我的组件:
ngOnInit(){
this.recordState = JSON.parse(localStorage['mystate']);
this.populateData();
}
我的测试:
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
spyOn(localStorage, 'getItem').and.callFake((key: string): String => {
return JSON.stringify({'mystate': {'testtext': 'hello'}});
});
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
错误:
should create FAILED
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at TestComponent.ngOnInit (webpack:///./src/app/TestComponent?:22:46)
at checkAndUpdateDirectiveInline (webpack:///./node_modules/@angular/core/fesm5/core.js?:9547:19)
at checkAndUpdateNodeInline (webpack:///./node_modules/@angular/core/fesm5/core.js?:10811:20)
at checkAndUpdateNode (webpack:///./node_modules/@angular/core/fesm5/core.js?:10773:16)
at debugCheckAndUpdateNode (webpack:///./node_modules/@angular/core/fesm5/core.js?:11406:38)
at debugCheckDirectivesFn (webpack:///./node_modules/@angular/core/fesm5/core.js?:11366:13)
at Object.eval [as updateDirectives] (ng:///DynamicTestModule/SearchActionsComponent_Host.ngfactory.js:10:5)
at Object.debugUpdateDirectives [as updateDirectives] (webpack:///./node_modules/@angular/core/fesm5/core.js?:11358:21)