我似乎找不到以下问题的示例。我对NGXS状态进行了单元测试:
describe('Project store', () => {
let store: Store;
let projectService: ProjectService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([ProjectState])]
}).compileComponents();
projectService = new ProjectService(); // error: needs httpClient
store = TestBed.get(Store);
}));
it('should load projects', () => {
const EXPECTED_PROJECTS = [
{
"id": "1",
"description": "abc"
},
{
"id": "1",
"description": "abc"
}
] as Project[];
spyOn(projectService, 'loadProjects').and.returnValue(EXPECTED_PROJECTS);
const expected: ProjectStateModel = {
loadedProjects: EXPECTED_PROJECTS,
createdProjects: []
};
store.dispatch(new LoadProjects());
const actual = store.selectSnapshot(ProjectState.getState);
expect(actual).toEqual(expected);
});
});
当ProjectService
本身需要httpClient
时,我该如何进行监视?
我找到了有关如何测试需要httpClient
的服务的示例,但是现在发现了有关如何模拟需要客户端的服务的示例。
现在我知道我可以自己编写一个模拟服务,但是我试图找出是否可以使用茉莉花间谍来完成。
答案 0 :(得分:0)
您可以使用HttpTestingController
来模拟服务中所需的响应,请参见以下代码:
describe('Project store', () => {
let store: Store;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
NgxsModule.forRoot([ProjectState])
],
providers: [ProjectService]
}).compileComponents();
store = TestBed.get(Store);
}));
it('should load projects',
inject([HttpTestingController], (controller: HttpTestingController) => {
const EXPECTED_PROJECTS = [
{ 'id': '1', 'description': 'abc' },
{ 'id': '1', 'description': 'abc' }
] as Project[];
const expected = {
'projectsState': <ProjectStateModel>{
loadedProjects: EXPECTED_PROJECTS,
createdProjects: []
}
};
store.dispatch(new LoadProjects());
// expecting one GET request as a result of LoadProjects action
const testReq = controller.expectOne(req => req.method === 'GET');
// provide mock response
testReq.flush(EXPECTED_PROJECTS);
const actual = store.selectSnapshot(ProjectState.getState);
expect(actual).toEqual(expected);
}));
});