gpt4 book ai didi

angular - 用于 Mockups 的 Mock Http 后端

转载 作者:可可西里 更新时间:2023-11-01 16:32:52 26 4
gpt4 key购买 nike

有没有办法模拟 Angular 2 的 Http 对象,梦想是将它用于模型,并拥有与核心代码相同的模型,除了发送到服务器的连接。

最佳答案

有一个 MockBackend,确保它在默认 Backend 之后在 DI 中注册,以便使用它 https://angular.io/docs/ts/latest/api/http/testing/MockBackend-class.html

import {DefaultOptions, Http} from 'angular2/http';
import {MockBackend} from 'angular2/http/testing';
it('should get some data', inject([AsyncTestCompleter], (async) => {
var connection;
var injector = Injector.resolveAndCreate([
MockBackend,
provide(Http, {useFactory: (backend, defaultOptions) => {
return new Http(backend, defaultOptions)
}, deps: [MockBackend, DefaultOptions]})]);
var http = injector.get(Http);
var backend = injector.get(MockBackend);
//Assign any newly-created connection to local variable
backend.connections.subscribe(c => connection = c);
http.request('data.json').subscribe((res) => {
expect(res.text()).toBe('awesome');
async.done();
});
connection.mockRespond(new Response('awesome'));
}));

如果你想为整个应用程序使用MockBackend

bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(XHRBackend, {useClass: MockBackend}),
provide(JSONPBackend, {useClass: MockBackend})]);

确保 MockBackend 提供程序在 HTTP_PROVIDERS 之后。

如果您希望MockBackend 仅由特定组件使用,请添加

provide(XHRBackend, {useClass: MockBackend}),
provide(JSONPBackend, {useClass: MockBackend})

改为组件的提供者列表。

关于angular - 用于 Mockups 的 Mock Http 后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34926808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com