使用 json 服务器模拟进行角度测试

问题描述

我是角度测试的新手,我正在尝试测试模拟的 json 是否等于 db.json 中的 json。问题是即使 json 服务器关闭,测试也会成功。这是我的规格:

import { Testbed } from '@angular/core/testing';
import { ProfileService } from './profile.service';
import { HttpClientTestingModule,HttpTestingController } from '@angular/common/http/testing';

describe('ProfileService',() => {
  // We declare the variables that we'll use for the Test Controller and for our Service
  let httpTestingController: HttpTestingController;
  let service: ProfileService;
  
  beforeEach(() => {
    Testbed.configureTestingModule({
      providers: [ProfileService],imports: [HttpClientTestingModule]
    });

    // We inject our service (which imports the HttpClient) and the Test Controller
    httpTestingController = Testbed.get(HttpTestingController);
    service = Testbed.get(ProfileService);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  describe('#getInfoContratto',() => {
    let expectedInfo = JSON.parse('{"abi": "string","banca": "string","cab": "string","cin": "string","codiceRID": "string","conto": "string","dataAllineamento": "string","dataAttivazione": "string","dataUltimaModifica": "string","iban": "string","intestatarioConto": "string","nome": "string","societa": "string","sportello": "string","stato": "string","statoAllineamento": "string","tipoGaranzia": "string","valoreDellaFidejussione": "string"}');

    it('should return expected info',() => {
      
      service.getInfoContratto("TEST").subscribe(
      infoContratti => expect(infoContratti).toEqual(expectedInfo,'should return expected info'),fail
      );

      const req = httpTestingController.expectOne({ method: 'POST',url: service.serverUrl+ "accesso-utenti-infoContratto" });
      // expect(req.request.method).toEqual('POST');

      req.flush(expectedInfo);
      console.log(req.request.url);
    });
    
  });

我做错了什么?

解决方法

好的,我想就此发表评论,但我认为评论本身就是一个答案。

即使 JSON 服务器 关闭,您的测试仍通过的原因是 HttpClientTestingModule

发生的情况是您的实际(在我们的应用程序被提供时发生)http 调用从未发生。它们被 mock 调用取代,这些调用由我们的 HttpClientTestingModule 在幕后完成。

问题:为什么会这样?

答案: 单元测试的本质是隔离servicecomponent,然后使用虚拟数据对其进行测试。因此,应始终避免真正的 http 调用,并应使用一些受控数据进行模拟。

由于您不熟悉单元测试,我建议您阅读 this article 并参考同一页面上的附加文章。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...