0
我试图测试我的Angular 2服务,它使用Observables和ngrx存储。我有大多数测试通过,但在我的一个测试中,我试图嘲笑HTTP调用,我相信我做的是正确的,但是我的问题是我的代码在“注入”语句中没有实际执行:Karma/Jasmine测试Angular 2服务不执行内部注入代码
@Injectable()
export class FirmService {
public stateObservable: Observable<FirmState>;
constructor(private $http: AuthHttp, private store: Store<FirmState>) {
// whatever reducer is selected from the store (in line below) is what the "this.store" refers to in our functions below.
// it calls that specific reducer function
this.stateObservable = this.store.select('firmReducer');
}
public getFirms(value?: string) {
return this.$http.get('/api/firm').map((response: Response) => {
this.store.dispatch({
type: firmActions.GET_FIRMS,
payload: response.json()
});
return;
});
}
}
我对getFirms测试:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule, AppModule],
providers: [
{ provide: XHRBackend, useClass: MockBackend },
FirmService
]
}));
// using these mock firms in other tests as well
firms = {
firms: [
{
'name': 'ICBC', 'country': 'United States', 'industry': 'Financial Services',
'edfModels': [{ 'name': 'US FIN 4.0', 'QO': false }, { 'name': 'US FIN 4.0', 'QO': true }],
'lgdModels': [{ 'name': 'US FIN 4.0', 'QO': false }, { 'name': 'US FIN 4.0', 'QO': true }],
'modifiedOn': '1/1/2016', 'modifiedBy': 'John Doe'
},
{
'name': 'CCBC', 'country': 'United States', 'industry': 'Financial Services',
'edfModels': [{ 'name': 'US FIN 4.0', 'QO': false }, { 'name': 'US FIN 4.0', 'QO': true }],
'lgdModels': [{ 'name': 'US FIN 4.0', 'QO': false }, { 'name': 'US FIN 4.0', 'QO': true }],
'modifiedOn': '1/1/2016', 'modifiedBy': 'John Doe', 'selected': true
}
]
};
});
it('getFirms should dispatch the GET_FIRMS action', inject([FirmService, XHRBackend], (firmServiceMock, mockBackend) => {
const expectedAction = {
type: firmActions.GET_FIRMS,
payload: firms
};
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(firms)
});
}));
spyOn(mockStore, 'dispatch');
firmServiceMock.getFirms().subscribe(() => {
expect(mockStore.dispatch).toHaveBeenCalled();
expect(mockStore.dispatch).toHaveBeenCalledWith(expectedAction);
});
}));
谁能告诉我什么,我需要做的,在我的规格文件中删除此错误: 类型错误:http.get(...)地图(... ).toPromise不是一个函数。
它不应该在我的服务执行http调用,如果我嘲笑它?
谢谢..看起来像我不得不把它移动到它的实际声明..我更新了我的代码,但现在我得到这个错误:“TypeError:http.get(...)。map(... ).toPromise不是一个函数“,当它到达我的firmServiceMock.getFirms()。订阅代码行时。我试过这个解决方案:https://stackoverflow.com/questions/39121286/angular2-typeerror-this-http-get-topromise-is-not-a-function。但是,当我添加错误停止,但没有代码运行在我的订阅功能。我已经添加了我正在测试的服务。谢谢 – bschmitty