Angular 2 模拟响应不起作用 [英] Angular 2 mock response not working
本文介绍了Angular 2 模拟响应不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 Angular 2 测试:
I have the following Angular 2 test:
/* tslint:disable:no-unused-variable */
import { provide } from '@angular/core';
import { MockBackend } from '@angular/http/testing';
import {
Http,
HTTP_PROVIDERS,
Response,
ResponseOptions,
BaseRequestOptions,
ConnectionBackend,
XHRBackend
} from '@angular/http';
import {
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject
} from '@angular/core/testing';
import { BookService } from './book.service';
describe('Book Service', () => {
beforeEachProviders(() => [
BookService,
HTTP_PROVIDERS,
MockBackend,
BaseRequestOptions,
{ provide: XHRBackend, useExiting: MockBackend },
provide(Http, {
useFactory: function (backend:ConnectionBackend, defaultOptions:BaseRequestOptions) {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
})
]);
it('should assign a list of books', inject([BookService, MockBackend, Http], (service, backend, http) => {
var response;
backend.connections.subscribe(c => {
expect(c.request.url).toEqual('/api/books.json');
c.mockRespond(new Response(new ResponseOptions({body: {message: 'thank you'}})));
});
http.get('/api/books.json').subscribe(data => response = data);
expect(response).toEqual({ message: 'thank you' });
}));
});
我想关注的部分是:
it('should assign a list of books', inject([BookService, MockBackend, Http], (service, backend, http) => {
var response;
backend.connections.subscribe(c => {
expect(c.request.url).toEqual('/api/books.json');
c.mockRespond(new Response(new ResponseOptions({body: {message: 'thank you'}})));
});
http.get('/api/books.json').subscribe(data => response = data);
expect(response).toEqual({ message: 'thank you' });
}));
当我运行测试时,我得到:
When I run the test, I get:
预期响应状态:null 为空 URL:null 等于 Object({ message: 'thank you }).
认为这可能是一个异步问题,我改变了我的期望:
Thinking it's maybe an async issue, I changed my expectation to this:
http.get('/api/books.json').subscribe(data => {
expect(data).toEqual({ message: 'thank you' });
});
但我仍然收到相同的失败消息.
But I'm still getting the same failure message.
我该怎么做才能使模拟响应生效?
What can I do to get the mock response to take effect?
推荐答案
这是解决方案.我只是不得不改变
Here's the solution. I just had to change
http.get('/api/books.json').subscribe(data => {
expect(data).toEqual({ message: 'thank you' });
});
到
http.get('/api/books.json').subscribe(data => {
expect(data.json()).toEqual({ message: 'thank you' });
});
所以我所要做的就是添加 .json()
部分并且它起作用了.
So all I had to do was add the .json()
part and it worked.
这篇关于Angular 2 模拟响应不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文