gpt4 book ai didi

unit-testing - Angular 5 中的 karma 测试。失败 : Http failure response

转载 作者:行者123 更新时间:2023-12-04 05:08:49 25 4
gpt4 key购买 nike

应用组件:

ngOninit(){
this.http.get('../assets/data/dummy.json').subscribe(result => {
this.favorites = result;
});
}

测试名称:AppComponent 应该在 h1 标签中呈现标题

Karma 消息:失败: http://localhost:9876/assets/data/dummy.json 的 Http 失败响应: 404 未找到

如果我在 get 方法中将 json 的绝对路径设为 http://localhost:4200/assets/data/dummy.json ,错误消失了

最佳答案

您的测试失败的原因是 ngOnInit()在您的组件中进行实际 http 调用以获取该资源,dummy.json .

良好的单元测试实践通常会说你应该模拟应用程序的大部分部分,除了被测单元。这为您提供了更多控制权,并使您的测试能够更好地解释出现故障时的错误所在。当我们对该资源使用实际的 http 调用时,测试失败了,我们不知道是因为没有检索到资源还是因为标题没有在 h1 中呈现。标签。这两个问题彼此无关,应该在单独的测试用例中。为此,我们模拟 http 调用,以便确保收到成功的响应,然后只关注标题。

为此,我们可以使用 HttpClientTestingModule .

这是app.component.ts的一个例子反射(reflect)你上面的例子:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-root',
template: `
<h1>{{ title }} app is running!</h1>
`
})
export class AppComponent implements OnInit {
favorites: {};
title = 'Demo';

constructor(private http: HttpClient) {}

ngOnInit() {
this.http.get('../assets/data/dummy.json').subscribe(result => {
this.favorites = result;
});
}
}


并让您的 AppComponent should render title in a h1 tag测试通过,这是您的规范文件, app.component.spec.ts :

import { TestBed, async } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';

import { AppComponent } from './app.component';

describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
imports: [ HttpClientTestingModule ]
}).compileComponents();
}));

it('AppComponent should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Demo app is running!');
});
});

请注意,我们为完成这项工作所做的是添加了 HttpClientTestingModule到我们的进口 list TestBed.configureTestingModule({}) .我们不需要做任何其他事情,当在这个 TestBed 中创建一个组件时并要求提供 HttpClient , TestBed将为它提供 HttpClient来自 HttpClientTestingModule .这将阻止您的所有请求实际发送,现在您的测试将通过。

这适用于您的情况,但现在它也允许您开始对 http 请求和响应执行测试。退房 https://angular.io/guide/http#testing-http-requests有关 HttpClientTestingModule 的更多信息和一般的http测试。

关于unit-testing - Angular 5 中的 karma 测试。失败 : Http failure response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48126724/

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