我有一项服务,当用户登录时,该服务将基本用户“配置”信息存储在会话存储中。然后,我在整个应用程序中调用该服务以在需要时返回配置。
export class ClientConfigService {
response: LoginConfig = initialClientConfig;
private configResponse = new BehaviorSubject(this.response);
configData = this.configResponse.asObservable();
constructor(private apiService: ApiService) { }
setSessionStorage(data: LoginConfig) {
sessionStorage.setItem('client', JSON.stringify(data));
this.configResponse.next(data);
}
getClientConfig(clientId: string) {
const clientSetup = { startUrl: `${environment.apiUrl}/${clientId}` };
return this.apiService.post(`yd-core/npb/start`, clientSetup).subscribe((data: LoginConfig) => {
this.configResponse.next(data);
});
}
getPageData() {
const sessionConfig: LoginConfig = JSON.parse(sessionStorage.getItem('config'));
return sessionConfig.client.config;
}
getClientId() {
const sessionConfig: LoginConfig = JSON.parse(sessionStorage.getItem('config'));
return sessionConfig.client.clientId;
}
getCurrentUser() {
const sessionConfig: LoginConfig = JSON.parse(sessionStorage.getItem('config'));
return sessionConfig.user;
}
}
[运行ng测试时,我得到了很多TypeError: Cannot read property 'client' of null
的实例
我知道我需要模拟会话存储。.我在这里尝试没有任何效果
import { TestBed } from '@angular/core/testing';
import { ClientConfigService } from './client-config.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { ApiService } from './api.service';
import { initialClientConfig } from '../models/user';
describe('ClientConfigService', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
window.sessionStorage.setItem('client', JSON.stringify({client : {} }));
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
RouterModule.forRoot([]),
],
providers: [
ApiService
]
})
.compileComponents();
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
});
it('should be created', () => {
const service: ClientConfigService = TestBed.get(ClientConfigService);
expect(service).toBeTruthy();
});
});
我可能会丢失一些东西,但是对我来说,您唯一设置sessionStorage
的时间是使用'client'键,但是每次从sessionStorage
中拉出时,您都在使用'config'键。难道只要您输入错了密码就可以吗?
我认为这更多是依赖注入问题。您期望这行有效:
const service: ClientConfigService = TestBed.get(ClientConfigService);
当ClientConfigService不属于测试模块的一部分时。另外,由于ClientConfigService依赖于ApiService,因此,您必须确保满足ApiService服务的依赖性要求。
理想情况下,在单元测试中,您一次只能测试一件事。我建议您通过更改此方法在此测试中模拟您的ApiService:
providers: [
ApiService
]
对此:
providers: [
{provide: ApiService, useValue: {"...mock properties here"}}
]
我希望这会有所帮助,以撒
问题是我只是简单地将密钥命名为错误。在做
window.sessionStorage.setItem('client', JSON.stringify({client : {} }));
而不是
window.sessionStorage.setItem('config', JSON.stringify(initialClientConfig))