【发布时间】:2023-04-05 00:39:01
【问题描述】:
我对单元测试完全陌生,我是第一次使用 jasmine/karma 实现单元测试。我在理解如何通过模拟 Http Post 来实现测试方面遇到了一些问题。我经历了一些解决方案,例如: solution1 和 solution2
但是我在理解它们时仍然遇到了一些问题,并且也遇到了一些错误。
通过以下解决方案2,我尝试实现如下:
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)
})
})
我收到的错误是这样的:
错误
无法读取未定义的属性“连接”
有人可以帮助我了解我哪里出错了。
此外,我希望收到任何可以帮助我更好地理解这一点的文档的参考。
【问题讨论】:
-
这里有一些文档可能会有所帮助:angular.io/guide/testing#testing-http-services
标签: angular unit-testing jasmine karma-jasmine