首页 > 解决方案 > 如何在 Angular 测试中打印调试消息?

问题描述

编辑:这个问题是完全错误的,因为 Angular DO NOT 在单元测试中调用 http 请求。您无法打印请求的真正响应。单元测试“伪造”请求的响应,然后实施。如果您遇到与我相同的问题,请再次阅读有关 Angular 单元测试的文档。


我想在单元测试中console.log("my text")或类似的东西。

the-cat-api.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TheCatApiService {
  private catApi="05f72f39-87d9-4166-b4f1-6dfb55db1744"
  private REST_API = "https://api.thecatapi.com/v1/images/search?api_key="
  constructor(private httpClient: HttpClient) { }

  getCat(){
    return this.httpClient.get(this.REST_API + this.catApi);
  }
  
}

the-cat-api.service.spec.ts

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {HttpClientModule} from '@angular/common/http';
import { TheCatApiService } from './the-cat-api.service';

describe('TheCatApiService', () => {
  let service: TheCatApiService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule], 
      providers: [TheCatApiService]
    });
    service = TestBed.inject(TheCatApiService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should return cat', () =>{
    service.getCat().subscribe((data) => {
      console.log("test the cat api ")
      console.log(data)
    })
  })
});

当我运行ng test它显示

➜  learn-service git:(master) ✗ ng test                           
10% building 2/2 modules 0 active24 07 2020 13:58:33.558:WARN [karma]: No captured browser, open http://localhost:9876/
24 07 2020 13:58:33.562:INFO [karma-server]: Karma v5.0.9 server started at http://0.0.0.0:9876/
24 07 2020 13:58:33.563:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
24 07 2020 13:58:33.567:INFO [launcher]: Starting browser Chrome
24 07 2020 13:58:39.580:WARN [karma]: No captured browser, open http://localhost:9876/
24 07 2020 13:58:39.724:INFO [Chrome 84.0.4147.89 (Linux x86_64)]: Connected on socket MWHJE0_oK6DZDg3_AAAA with id 30651510
WARN: 'Spec 'TheCatApiService should return cat' has no expectations.'
Chrome 84.0.4147.89 (Linux x86_64): Executed 5 of 6 SUCCESS (0 secs / 0.276 secs)
Chrome 84.0.4147.89 (Linux x86_64): Executed 6 of 6 SUCCESS (0.409 secs / 0.282 secs)

我检查了 chrome(Karma 测试框架)的开发者控制台,但没有看到控制台日志。

标签: angulartypescriptunit-testingkarma-jasmine

解决方案


这个问题是完全错误的,因为 Angular DO NOT 在单元测试中调用 http 请求。您无法打印请求的真正响应。单元测试“伪造”请求的响应,然后实施。如果您遇到与我相同的问题,请再次阅读有关 Angular 单元测试的文档。

https://angular.io/guide/http#testing-http-requests


推荐阅读