javascript - Angular 4 中的 HTTP post 请求单元测试

标签 javascript angular unit-testing testing karma-jasmine

这个测试现在正在运行

我想在 Angular 2 中测试 HTTP 请求,但它不起作用。 这是错误消息: .../loginservice.service.spec.ts (45,11) 中的错误:';'预期。 .../loginservice.service.spec.ts (45,12) 中的错误:预期为“)”。

代码如下: 这是一个发布请求,并且工作正常。

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';  

@Injectable()
export class LoginService {

    constructor(private http: Http) { }

    postLoginDetails(loginDetails): Observable<Comment[]> {
        const endpoint = 'http://localhost:8080/api/login';
        const bodyString = loginDetails;
        const headers = new Headers({ 'Content-Type': 'application/json'});
        const options = new RequestOptions({headers: headers});

        return this.http.post(endpoint, bodyString, options)
            .map((res: Response) => res.json())
            .catch((error: any) =>  Observable.throw(error.json().error || 'server error'));
    }
}

这是对它的测试: 这是post请求的测试。我使用了不同的文章来编写它,也许这就是它不起作用的原因。

import { TestBed, inject } from '@angular/core/testing';
import {
    HttpModule,
    Http,
    XHRBackend,
    ResponseOptions,
    Response,
    Headers
} from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

import { LoginService } from './loginservice.service';

describe('LoginService', () => {

    beforeEach(() => {

        TestBed.configureTestingModule({
            imports: [HttpModule],
            providers: [
                LoginService,
                { provide: XHRBackend, useClass: MockBackend },
            ]
        });
    });

    describe('postLoginDetails()', () => {
        it('should return an Observable<Comment[]> with ok status', 
inject([LoginService, XHRBackend], (LoginService, MockBackend) => {
            const mockResponse = {
                    status: 'ok',
                    token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRlc3RBZG1pbiIsImFkbWluIjp0cnVlfQ.nhC1EDI5xLGM4yZL2VMZyvHcbcWiXM2RVS7Y8Pt0Zuk'
                }

            const loginDetails = {
                email: 'test@example.com',
                password: '1234'
                };
            MockBackend.connections.subscribe((connection) => {
                connection.mockRespond(new Response(new ResponseOptions({
                    body: JSON.stringify(mockResponse)
                })));
            });
            LoginService.postLoginDetails(loginDetails).subscribe((mockResponse) => {
                expect(mockResponse.status).toEqual('ok');
            });
        }));
    });
});

最佳答案

关闭 mockBackend.connections 时 不匹配

   describe('postLoginDetails()', () => {
        it('should return an Observable<Comment[]>', inject([LoginService, XHRBackend], (loginService, mockBackend) => {
            const mockResponse = {
                    status: 'ok',
                    token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRlc3RBZG1pbiIsImFkbWluIjp0cnVlfQ.nhC1EDI5xLGM4yZL2VMZyvHcbcWiXM2RVS7Y8Pt0Zuk'
            };

        mockBackend.connections.subscribe((connection) => {
            const loginDetails = {
                email: 'test@example.com',
                password: '1234'
                };
            loginService.postLoginDetails(loginDetails).subscribe((userInfo) => {
                expect(userInfo.length).toBe(2);
                expect(userInfo.status).toEqual('ok');
            });

        }));
    });
});

更新:- 修复了一些语法错误。

关于javascript - Angular 4 中的 HTTP post 请求单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44654047/

相关文章:

javascript - readystatechange 使用 addEventListener 与旧式属性?

html - 在 Ionic Angular 项目上的 HTML5 视频标签上播放/暂停

unit-testing - 您如何对使用计时器的 Rx 运算符进行单元测试?

typescript - 引用错误 : MediaStream is not defined - in unitTest with Jest

c# - 从多个线程进行单元测试的最佳方法是什么?

javascript - 如何提取仅在 Javascript 中具有多个值的数组数据?

javascript - CasperJS/PhantomJS 段错误

javascript - Vue 组件在 <template> html 标签中不可见

node.js - 在 Linux Jenkins CI 上使用 Windows 中的 node_modules...好还是坏?

javascript - 如何在鼠标悬停时在其他内容之上放大 div 以减少滚动溢出内容的需要?我正在使用 Angular 2/4