[英]How do I test an endpoint using Jasmine/Karma?
I have a method in one of my components that hits an endpoint like this...我的一个组件中有一个方法可以达到这样的端点......
private async getRolesAsync(): Promise<void> {
const roles = await this.http.get<any>('https://jsonplaceholder.typicode.com/todos/1').toPromise();
this.data = roles;
}
Notice I have a fake endpoint in there, but what I'd like to know is how do I test that in a unit test?请注意,我在那里有一个假端点,但我想知道如何在单元测试中测试它? I want a unit test that tests to see if the endpoint works, ie, it returns a 200 success.
我想要一个单元测试来测试端点是否有效,即它返回 200 成功。
I'm using Angular 13 as my application framework and Jasmine/Karma as my unit testing framework.我使用 Angular 13 作为我的应用程序框架,使用 Jasmine/Karma 作为我的单元测试框架。
Please use this end-to-end running code for the resolution of all your issues.请使用此端到端运行代码来解决您的所有问题。
spec.ts file - spec.ts 文件 -
import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing";
import { TestBed, async, ComponentFixture } from "@angular/core/testing";
import { RouterTestingModule } from "@angular/router/testing";
import { AppComponent } from "./app.component";
describe("AppComponent", () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let httpTestingController: HttpTestingController;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
HttpClientTestingModule,
],
declarations: [AppComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
httpTestingController = TestBed.inject(HttpTestingController)
fixture.detectChanges();
});
it('#getRolesAsync should return expected data', async (done) => {
const expectedData = {
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
};
(await component.getData()).subscribe(data => {
expect(data).toEqual(expectedData);
done();
});
const testRequest = httpTestingController.expectOne('https://jsonplaceholder.typicode.com/todos/1');
testRequest.flush(expectedData);
});
});
component.ts file - component.ts 文件 -
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"],
})
export class AppComponent {
data: any;
constructor(private http: HttpClient) { }
async getData(): Promise<Observable<any>> {
const roles = await this.http.get<any>('https://jsonplaceholder.typicode.com/todos/1');
return this.data = roles;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.