如何解决使用 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
在幕后完成。
问题:为什么会这样?
答案: 单元测试的本质是隔离service
或component
,然后使用虚拟数据对其进行测试。因此,应始终避免真正的 http 调用,并应使用一些受控数据进行模拟。
由于您不熟悉单元测试,我建议您阅读 this article 并参考同一页面上的附加文章。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。