首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角4:利用mockRespond与RxJS观测资料

角4:利用mockRespond与RxJS观测资料
EN

Stack Overflow用户
提问于 2017-05-10 00:28:25
回答 1查看 781关注 0票数 0

我最近构建了一个可以工作的应用程序,我正在尝试构建一个测试。我的服务从API后端获取项目:

代码语言:javascript
复制
export class CatfactService {

    constructor(private http: Http) {}
    getFacts() {
        const url = "http://www.catfact.info/api/v1/facts.json";
        return this.http.get(url).map(this.extractData)
            .catch(this.handleError);
    }

在我的组件中,我能够订阅API响应。facts变量的结果是API的响应详细信息:

代码语言:javascript
复制
ngOnInit() {
    this.counter = this.start;
    this.service.getFacts().subscribe((facts) => {
        this.results = facts.facts;
    });
}

现在,我正在为服务构建一个测试,奇怪的是,订阅方法获得了参数,但它返回的不是作为响应数据的参数,而是返回最终解析为模拟值的承诺。

代码语言:javascript
复制
import {
    TestBed,
    inject,
    fakeAsync,
    tick
} from '@angular/core/testing';

import {
    CatfactService
} from './catfact.service';
import {
    HttpModule,
    Http,
    BaseRequestOptions,
    XHRBackend,
    ResponseOptions
} from '@angular/http';
import {
    MockBackend
} from '@angular/http/testing';
describe('CatfactService', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpModule],
            providers: [
                CatfactService,
                MockBackend,
                BaseRequestOptions,
                {
                    provide: Http,
                    useFactory: (backend, options) => new Http(backend, options),
                    deps: [MockBackend, BaseRequestOptions]
                }
            ],
            imports: [
                HttpModule
            ]
        });
    });

    it('should return reasonable json', inject([CatfactService, MockBackend], fakeAsync((service: CatfactService, mockBackend) => {

        const mockResponse = {
            data: [{
                    id: 0,
                    details: 'All cats are lions'
                },
                {
                    id: 1,
                    details: 'Video 1'
                },
                {
                    id: 2,
                    details: 'Video 2'
                },
                {
                    id: 3,
                    details: 'Video 3'
                },
            ]
        };

        mockBackend.connections.subscribe(connection => {
            connection.mockRespond(new Response(JSON.stringify(mockResponse)));
        });

        service.getFacts().subscribe((facts) => {
            facts.then((facts2) => {
                expect(facts2.length).toBe(4);
                expect(facts2[0].details).toEqual("All cats are lions");
            });
        });

        tick();
    })));
});

调用订阅方法返回实际应用程序中的实际响应,但在测试中作出承诺,这使我相信我在应用程序中错误地设置了对数据的模拟。

我正在使用以下版本的角:

代码语言:javascript
复制
ng -v
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/
@angular/cli: 1.0.2
node: 7.9.0
os: darwin x64
@angular/common: 4.1.1
@angular/compiler: 4.1.1
@angular/core: 4.1.1
@angular/forms: 4.1.1
@angular/http: 4.1.1
@angular/platform-browser: 4.1.1
@angular/platform-browser-dynamic: 4.1.1
@angular/router: 4.1.1
@angular/cli: 1.0.2
@angular/compiler-cli: 4.1.1

整个项目都是在GitHub上完成的:https://github.com/kenmazaika/AngularTesting

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-10 05:42:11

这里是规范的一个固定版本。主要问题是,您没有导入角响应

代码语言:javascript
复制
            import { TestBed, inject, fakeAsync, tick } from '@angular/core/testing';

            import { CatfactService } from './catfact.service';
            import { HttpModule, Http, BaseRequestOptions, XHRBackend, ResponseOptions, Response, RequestOptions } from '@angular/http';
            import { MockBackend } from '@angular/http/testing';
            describe('CatfactService', () => {
                beforeEach(() => {
                    TestBed.configureTestingModule({
                        imports: [HttpModule],
                        providers: [
                            CatfactService,
                            MockBackend,
                            BaseRequestOptions,
                            {
                                provide: Http,
                                useFactory: (backend, options) => new Http(backend, options),
                                deps: [MockBackend, BaseRequestOptions]
                            }
                        ]
                    });
                });

                it('should return reasonable json', inject([CatfactService, MockBackend], fakeAsync((service: CatfactService, mockBackend) => {

                    const mockResponse = {
                        data: [
                            { id: 0, details: 'All cats are lions' },
                            { id: 1, details: 'Video 1' },
                            { id: 2, details: 'Video 2' },
                            { id: 3, details: 'Video 3' },
                        ]
                    };

                    mockBackend.connections.subscribe(connection => {
                        connection.mockRespond(new Response(
                            new ResponseOptions({
                                body: [
                                    { id: 0, details: 'All cats are lions' },
                                    { id: 1, details: 'Video 1' },
                                    { id: 2, details: 'Video 2' },
                                    { id: 3, details: 'Video 3' },
                                ]
                            })));
                    });

                    service.getFacts().subscribe((facts) => {
                        expect(facts.length).toBe(4);
                        expect(facts[0].details).toEqual("All cats are lions");
                    });

                    tick();
                })));
            });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43881799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档