在Angular 5中进行Karma测试.失败:Http失败响应 [英] Karma testing in Angular 5. Failed: Http failure response

查看:50
本文介绍了在Angular 5中进行Karma测试.失败:Http失败响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

appComponent:

appComponent:

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

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

test name: AppComponent should render title in a h1 tag

业力消息:失败: http://localhost:9876/assets/的Http故障响应data/dummy.json :找不到404

Karma message: Failed: Http failure response for http://localhost:9876/assets/data/dummy.json: 404 Not Found

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

If i put absolte path to json in the get method as http://localhost:4200/assets/data/dummy.json, the error is gone

推荐答案

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

The reason your test is failing is because the ngOnInit() in your component is making an actual http call to get that resource, dummy.json.

良好的单元测试实践通常会说,您应该模拟应用程序的大部分部分,除了被测单元.这样可以给您更多的控制权,并且可以使您的测试更好地解释发生故障时错误在哪里.当我们使用对该资源的实际http调用而测试失败时,我们不知道是否是因为未检索到该资源,或者是因为标题未在h1标记中呈现.这两个问题彼此无关,应该在单独的测试用例中进行.为此,我们模拟了http调用,以便确保收到成功的响应,然后仅关注标题.

Good unit testing practices usually say that you should mock most portions of your application, except for the unit under test. This gives you more control, and allows your tests to explain better where the error is when you have a failure. When we use the actual http call to that resource, and the test fails, we do not know if it is because the resource wasn't retrieved or because the title was not rendered in an h1 tag. These two issues have nothing to do with each other, and should be in separate test cases. To do this, we mock the http call so we can ensure a successful response is received and then only focus on the title.

为此,我们可以使用HttpClientTestingModule.

这是app.component.ts的示例,可以在上面反映您的示例:

This is an example of app.component.ts to reflect your example above:

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:

And to make your AppComponent should render title in a h1 tag test pass, this is your spec file, 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添加到TestBed.configureTestingModule({})中的进口清单中.我们无需执行其他任何操作,当在此TestBed中创建组件并要求提供HttpClient时,TestBed将为它提供来自HttpClientTestingModuleHttpClient.这样可以防止您的所有请求被实际发送,现在您的测试将通过.

Notice, what we did to make this work is that we added HttpClientTestingModule to our list of imports in TestBed.configureTestingModule({}). We don't need to do anything else, when a component is created in this TestBed and asks for an HttpClient, the TestBed will provide it with the HttpClient from the HttpClientTestingModule. This will prevent all of your requests from actually being sent, and now your test will pass.

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

This worked for your case, but it also now lets you start performing tests on the http requests and responses. Check out https://angular.io/guide/http#testing-http-requests for much more info about HttpClientTestingModule and http testing in general.

这篇关于在Angular 5中进行Karma测试.失败:Http失败响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆