angular - 为帖子编写业力测试用例并以 Angular 8 获得服务
问题描述
我是 Karma 的新手,不知道如何为 POST 方法编写测试用例。
这是我的 service.ts 文件:-
constructor(private httpclient: HttpClient) { }
url = 'http://localhost:8047/some_url';
check: Check[];
public newBehaviour = new BehaviorSubject<Check[]>([]);
postRents(hire, bookingId, trackingId): Observable<Check> {
hire.bookingId = bookingId;
hire.trackingId = trackingId;
return this.httpclient.post<Check>(this.url, hire, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
})
}).pipe(
tap(data => {
this.check.push(hire);
this.newBehaviour.next(this.check);
console.log(data);
})
);
如何测试此代码的 POST ?
编辑:-无法为此测试 POST
postRents(hire, bookingId, trackingId): Observable<Check> {
hire.bookingId = bookingId;
hire.trackingId = trackingId;
return this.httpclient.post<Check>(this.url, hire, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
})
}).pipe(
tap(data => {
this.check.push(hire);
this.newBehaviour.next(this.check);
console.log(data);
})
);
在方法实现中出现错误
it('Check Serivice', () => {
const mockData: RentBook[] = [{
rentingId: 343,
userName: 'dwew',
phone: 242324,
bookId: '3442',
startDate: new Date(),
endDate: new Date('Wed November 20 2019 00:00:00 GMT+0530 (India Standard Time)'),
}];
service.postRents(mockData, bookId: '34', rentId:34).subscribe(
res => expect(res).toEqual(mockData)
);
httpTestingController.expectOne(req => req.url.includes('http://localhost:8047/renting-app/api/v1/rentings') && req.method === 'POST')
.flush(mockData);
httpTestingController.verify();
});
任何传递参数数据的解决方案。不知道如何通过测试用例。
解决方案
用于HttpTestingController
编写服务测试
- 导入
HttpClientTestingModule
您的 TestBed 并使用 TestBedHttpTestingController
作为变量注入 - 这是一个简单的例子:
let mockHttp: HttpTestingController
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
...
})
mockHttp = TestBed.get(HttpTestingController);
describe('...', () => {
it('...', () => {
yourService.funcWhatToTest().subscribe(
res => expect(res).toEqual(yourMockData);
)
mockHttp.expectOne(req => req.url.includes('yourUrl') && req.method == 'POST' && ...)
.flush(yourMockData);
mockHttp.verify();
}
})
- 这个测试网上会有很多资源。用关键字搜索
HttpTestingController
推荐阅读
- javascript - React.js 模态不显示语义 Ui
- python - 在 Selenium 中关闭或禁用离开站点警报
- java - 这行代码是什么意思....new URLClassLoader(new URL[0],getClass().getClassLoader());
- javascript - localStorage 值不会自动更新
- ios - 如何使用本地 WIFI 连接将 iPhone 应用程序(其余)连接到 XAMPP?
- javascript - 如何动态添加到 jQuery 队列?
- mysql - 如何根据两个表中的多个值删除一个表的值
- bazel - Bazel:使 genrule 输出可用于另一个规则
- c - ATMEGA328p 将模拟值转换为电压
- php - 模态显示1人以上生日数据