问题描述
我对单元测试完全陌生,我第一次使用jasmine/karma进行单元测试.在理解如何通过模拟Http Post实现测试方面,我遇到了几个问题.我经历了一些解决方案,例如: solution1 和 solution2
I am completely new to unit testing and I am implementing unit testing using jasmine/karma for the first time. I am facing few issues in understanding how I should implement testing by mocking for Http Post. I have gone through few solutions such as :solution1 and solution2
但是我在理解它们时仍然遇到了一些问题,并且也遇到了一些错误.
But still I have faced few issues in understanding them and have also faced few errors.
通过solution2之后,我尝试实现以下方法:
By following solution2 I have tried to implement as follows:
http.service.ts
update(id,password,url){
let content = {
"username": id,
"password":password,
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(url,content,httpOptions).subscribe((data:any) => {
if(data.length){
return true;
}
else{
return false;
}
})
http.service.spec.ts
import { TestBed, inject } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { HttpService } from './http.service';
import {HttpModule, XHRBackend,Response,ResponseOptions, Connection} from
'@angular/http';
import { of } from 'rxjs';
import { MockBackend } from '@angular/http/testing';
describe('HttpService', () => {
let mockbackend, service;
beforeEach(() => {TestBed.configureTestingModule({
imports:[HttpClientModule, HttpModule],
providers:[{
provide: XHRBackend, useclass: MockBackend
}]
})
});
beforeEach(inject([ XHRBackend], (_service,
_mockbackend) => {
service = _service;
mockbackend = _mockbackend;
}));
it('post method is successfull',() =>{
const status = 'success';
const username = '5555555';
const password = 'test';
const currentUserExpected = JSON.stringify({status:status});
const response = { status : status};
const responseOptions = new ResponseOptions();
responseOptions.body = JSON.stringify(response);
mockbackend.connections.subscribe(connection =>{
connection.mockRespond(new Response(responseOptions));
});
service.update(username,password).subscribe(respond =>{
expect(respond).toEqual(true)
})
})
我收到的错误是这样的:
The error I am receiving is this:
错误
有人可以帮助我了解我要去哪里的问题.
Can someone please help me out in understanding where I am going wrong.
我也希望收到对任何文档的参考,这些文档可以帮助我更好地理解这一点.
Also I would like to receive reference to any documentation which can help me better understand this.
推荐答案
以下示例可能会有所帮助:employee-home.service.ts
Here is an example that may help:employee-home.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Employee } from '../models/employee';
import { USER_PROFILE_API_LOCATION } from '../../serviceConstants';
@Injectable({
providedIn: 'root'
})
export class EmployeeHomeService {
constructor(private http: HttpClient) {}
retrieveEmployee(): Observable<Employee> {
return this.http.get<Employee>(USER_PROFILE_API_LOCATION);
}
updateEmployee(employee: Employee): Observable<Employee> {
return this.http.put<Employee>(USER_PROFILE_API_LOCATION, employee);
}
}
然后:employee-home.service.spec.ts
and then: employee-home.service.spec.ts
import { asyncData, asyncError } from '@bis-angular/shared-helpers-testing';
import { EmployeeHomeService } from './employee-home.service';
import { Employee } from '../models/employee';
import { HttpErrorResponse } from '@angular/common/http';
import { EMPLOYEE } from '../../../fixtures/employee-fixture';
describe('EmployeeHomeService', () => {
describe('retrieveEmployee function', () => {
let httpClientSpyGet: { get: jasmine.Spy };
let employeeHomeServiceGet: EmployeeHomeService;
beforeEach(() => {
httpClientSpyGet = jasmine.createSpyObj('HttpClient', ['get']);
employeeHomeServiceGet = new
EmployeeHomeService(<any>httpClientSpyGet);
});
it('should return expected employee (HttpClient called once)', () => {
const expectedEmployee: Employee = EMPLOYEE;
httpClientSpyGet.get.and.returnValue(asyncData(expectedEmployee));
employeeHomeServiceGet
.retrieveEmployee()
.subscribe(employee => expect(employee).toEqual(expectedEmployee, 'expected employee'), fail);
expect(httpClientSpyGet.get.calls.count()).toBe(1, 'one call');
});
it('should return an error when the server returns an error', () => {
const errorResponse = new HttpErrorResponse({
error: 'test error',
status: 404,
statusText: 'Not Found'
});
httpClientSpyGet.get.and.returnValue(asyncError(errorResponse));
employeeHomeServiceGet
.retrieveEmployee()
.subscribe(
employee => fail('expected an error, not employee'),
error => expect(error.error).toContain('test error')
);
});
});
describe('updateEmployee function', () => {
let httpClientSpyPut: { put: jasmine.Spy };
let employeeHomeServicePut: EmployeeHomeService;
const expectedEmployee: Employee = EMPLOYEE;
beforeEach(() => {
httpClientSpyPut = jasmine.createSpyObj('HttpClient', ['put']);
employeeHomeServicePut = new EmployeeHomeService(<any>httpClientSpyPut);
});
it('should save employee (HttpClient called once)', () => {
httpClientSpyPut.put.and.returnValue(asyncData(expectedEmployee));
employeeHomeServicePut
.updateEmployee(expectedEmployee)
.subscribe(employee => expect(employee).toEqual(expectedEmployee, 'expected employee'), fail);
expect(httpClientSpyPut.put.calls.count()).toBe(1, 'one call');
});
it('should return an error when the server returns an error', () => {
const errorResponse = new HttpErrorResponse({
error: 'test error',
status: 404,
statusText: 'Not Found'
});
httpClientSpyPut.put.and.returnValue(asyncError(errorResponse));
employeeHomeServicePut
.updateEmployee(expectedEmployee)
.subscribe(
employee => fail('expected an error, not employee'),
error => expect(error.error).toContain('test error')
);
});
});
});
helpers:async-observable-helpers.ts
helpers: async-observable-helpers.ts
import { defer } from 'rxjs';
export function asyncData<T>(data: T) {
return defer(() => Promise.resolve(data));
}
export function asyncError<T>(errorObject: any) {
return defer(() => Promise.reject(errorObject));
}
这篇关于通过模拟Http Post-Angular 5使用jasmine/karma实现单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!