gpt4 book ai didi

Angular Testing 获取实际的 HTTP 响应

转载 作者:行者123 更新时间:2023-12-05 04:06:42 27 4
gpt4 key购买 nike

我是 Angular 单元测试的新手。我想要做的是从我的 API 获得实际结果。我检查了 this文档,但据我所知,我应该创建模拟响应。这是我的代码,

我的服务.ts:

...

public GetAll = (apiname: string): Observable<Object> => {

return this._http.get("foo/" + apiname,{headers:this.options}); //this.options = newHttpHeaders({'ContentType':'application/json','Accept':'application/json'});
}
...

我的服务.spec.ts:

...

beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientTestingModule
],
providers: [
MyService
]
});
});

afterEach(inject([HttpTestingController], (backend: HttpTestingController) => {
backend.verify();
}));

it('GetAll() should work', () => {

const testData = {id: "123"};

service.GetAll("items").subscribe(data => {
//console.log(JSON.stringify(data));
});

const req = httpTestingController.expectOne('foo/items');
expect(req.request.method).toEqual('GET');

req.flush(testData);
httpTestingController.verify();
});

当我在控制台中写入结果时,它会写入“testData”而不是“data”。正如我之前所说,我想从我的 API 中获得实际结果,而不是模拟结果。对不起,如果这是一个愚蠢的问题,但我该怎么做呢?感谢您的建议。

最佳答案

这是获取真实数据的有效解决方案

auth.service.te

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
interface Post {
userId: number;
id: number;
title: string;
body: string;
}
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private http: HttpClient) {}
getPost(postId: number): Observable<Post> {
return this.http.get<Post>(
`https://jsonplaceholder.typicode.com/posts/${postId}`
);
}
}

auth.service.spec.ts

import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
import { HttpClientModule } from '@angular/common/http';
interface Post {
userId: number;
id: number;
title: string;
body: string;
}
describe('AuthService', () => {
let service: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule],
});
service = TestBed.inject(AuthService);
});
it('should get the data successfully', (done: DoneFn) => {
service.getPost(1).subscribe((post: Post) => {
console.log('data is ', post);
expect(post.id).toEqual(1);
done();
});
});
});

enter image description here希望能有所帮助

关于 Angular Testing 获取实际的 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49550041/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com