angular - 如何在 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 测试框架)的开发者控制台,但没有看到控制台日志。
解决方案
这个问题是完全错误的,因为 Angular DO NOT 在单元测试中调用 http 请求。您无法打印请求的真正响应。单元测试“伪造”请求的响应,然后实施。如果您遇到与我相同的问题,请再次阅读有关 Angular 单元测试的文档。
推荐阅读
- ios - iOS 后台访问令牌刷新
- wordpress - WordPress 自定义 REST API 端点不返回数据
- regex - 从文件行中提取、打印和使用特定字符串作为变量
- swift - 如何在 xctest 中使用 swift 单击地图注释时访问标注视图
- vb.net - 通过代码添加资源时,RESX 文件的 Designer.vb 不更新
- java - docker-compose selenium-grid,maven,java。用于设置功能的空 VM 池
- mysql - 如何自动化mysql复制数据库?
- javascript - 从 typescript 调用转义 url 中的特殊字符以到达 mvc 控制器
- aframe - 当我单击 a-frame 中的 VR 按钮时,我无法查看它
- arrays - 如何显示对象数组中的标题?