【问题标题】:Angular testing with json server mock使用 json server mock 进行角度测试
【发布时间】:2021-05-21 10:24:53
【问题描述】:

我是角度测试的新手,我正在尝试测试模拟的 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);
    });
    
  });

我做错了什么?

【问题讨论】:

  • 有什么理由取消选择答案?查看 google 或 SO 时,选择的答案总是很有帮助

标签: angular unit-testing karma-jasmine json-server


【解决方案1】:

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

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

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

问题:为什么会这样?

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

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

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 2019-05-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    相关资源
    最近更新 更多