模拟对象在Angular jasmine单元测试中的工作原理

模拟对象在Angular jasmine单元测试中的工作原理,angular,angular-httpclient,Angular,Angular Httpclient,我正在学习单元测试和角度测试,所以我是这两方面的初学者。 我已经在angular中参考了一些关于http单元测试的教程和文章 我无法理解httpMock使用HttpTestingController做什么。我们称之为实际服务的函数,为什么我们称之为mock呢? 什么是潜在的过程? 请参考一些文章以更好地理解 提前谢谢 编辑: 这就是我坚持使用httpMock的地方。模拟服务的想法是,您不需要使用实际的功能(真正的http调用),但您确实需要服务方法来运行代码,没有任何异常 例如: 您有一个组件,

我正在学习单元测试和角度测试,所以我是这两方面的初学者。 我已经在angular中参考了一些关于http单元测试的教程和文章

我无法理解httpMock使用HttpTestingController做什么。我们称之为实际服务的函数,为什么我们称之为mock呢? 什么是潜在的过程? 请参考一些文章以更好地理解

提前谢谢

编辑:
这就是我坚持使用httpMock的地方。

模拟服务的想法是,您不需要使用实际的功能(真正的http调用),但您确实需要服务方法来运行代码,没有任何异常

例如: 您有一个组件,它在某些情况下通过Http从某个API收集数据。 其中一个单元测试应该测试您的组件是否进行了调用,但是如果有真正的调用,您根本不在乎。单元测试的重点是测试调用是否发生

编辑: 如果某些内部逻辑调用以收集数据以显示某些内容,也会发生同样的情况。您应该模拟http调用并返回自己的数据。你的单元测试不应该依赖外部的东西。假设您的测试将在没有internet的环境中运行。考试随时都可以通过


无论您测试的是哪种服务,此场景都适用。单元测试应具有单一责任。他们不应该依赖任何不同于其主要目的的东西。

让我们以我的一个文件为例,好吗

从“../../../../../model/SimpleConfiguration”导入{SimpleConfiguration};
从“../../../session/session.service”导入{SessionService};
从“@angular/core/testing”导入{TestBed};
从“@angular/router/testing”导入{RouterTestingModule};
从“./configuration.service”导入{ConfigurationService};
从“@angular/common/http/testing”导入{HttpClientTestingModule,HttpTestingController};
描述('ConfigurationService',()=>{
让httpock:HttpTestingController;
let服务:配置服务;
const createFakeFile=(文件名:string='fileName'):File=>{
constblob=newblob([''],{type:'text/html'});
blob['lastModifiedDate']='';
blob['name']=文件名;
返回斑点;
};
在每个之前(()=>{
TestBed.configureTestingModule({
进口:[
路由器测试模块,
HttpClientTestingModule
],
提供者:[配置服务,会话服务]
});
httpMock=TestBed.get(HttpTestingController);
service=TestBed.get(配置服务);
});
它('应该创建',完成=>{
expect(service.toBeTruthy();
完成();
});
它('getConfigurations应该在postes sources/:posted/configuration',(done)=>{
getConfigurations(0).subscribe(res=>done());
const successRequest=httpMock.expectOne(service.URL+'postes sources/0/configurations');
expect(successRequest.request.method).toEqual('GET');
successRequest.flush(空);
httpMock.verify();
});
它('uploadFile应该在postes源上发布/:postID/配置',(完成)=>{
uploadFile(0,createFakeFile(),new SimpleConfiguration()).subscribe(res=>done());
const successRequest=httpMock.expectOne(service.URL+'postes sources/0/configurations');
expect(successRequest.request.method).toEqual('POST');
successRequest.flush(空);
httpMock.verify();
});
它('updateComment应该在postes源上发布/:postID/configurations/:confID',(完成)=>{
updateConfiguration(0,0,新的SimpleConfiguration()).subscribe(res=>done());
const successRequest=httpMock.expectOne(service.URL+'postes sources/0/configurations/0');
expect(successRequest.request.method).toEqual('POST');
successRequest.flush(空);
httpMock.verify();
});
它('GetComponentInformation应在postes源上获取/:postID/tranches/:trancheID/Parameters',(完成)=>{
getComponentInformation(0,0).subscribe(res=>done());
const successRequest=httpMock.expectOne(service.URL+'postes sources/0/tranches/0/parameters');
expect(successRequest.request.method).toEqual('GET');
successRequest.flush(空);
httpMock.verify();
});
});
让我一步一步向你详细解释

  • 我们从描述测试开始。它允许我们对测试进行分组。在本例中,我们按功能对测试进行分组,我们的功能是一个名为ConfigurationService的服务。然后我们提供一个回调函数:这是Jasmine将运行的函数,用于运行测试

  • 接下来,我们声明变量。在这里,我们声明了两个变量和一个函数:
    httpMock
    service
    createFakeFile()
    。这些变量在整个测试组中都很有用,所以我们在顶层声明它们

  • 然后是每次测试之前的
    :在每次测试之前,将运行此函数,以执行某些操作。在本例中,它将创建一个测试平台:这是一些样板代码,将创建某种角度模块,以允许您的测试像在实际角度应用程序中一样运行

  • 在这个测试平台中,您需要声明您的依赖关系:因为我正在测试HTTP服务,所以我必须导入HTTP测试模块,因为我的测试使用路由,所以我还必须导入路由器测试模块。我还需要导入正在测试的服务,并且导入一个
    SessionService
    ,因为我也在服务中使用它

    之后,我通过
    TestBed获取这些依赖项的服务实例。get
    :这将允许我监视它们的属性,并查看它们的值以及它们是否被调用。这也将允许我调用我想要的函数
    descripe('randomService', () -> {
    
    }
    
    descripe('randomService', () -> {
        let randomService: RandomService;         
    }
    
    descripe('randomService', () -> {
       let randomService: RandomService;         
       beforeEach(() => {
           imports: [
               HttpClientTestingModule
           ]
       });
    }
    
    descripe('randomService', () -> {
       let randomService: RandomService;
       httpClientSpy;
    
       beforeEach(() => {
           imports: [
               HttpClientTestingModule
           ]
       });
       httpClientSpy = jasmine.CreateSpyObj('Http', ['get']);
       randomService = new RandomService(<any> httpclientSpy);       
    }
    
    descripe('randomService', () -> {
       let randomService: RandomService;
       httpClientSpy;
       mockResponse = { 1: ['first', 'second', 'third'] };
       beforeEach(() => {
           imports: [
               HttpClientTestingModule
           ]
       });
       httpClientSpy = jasmine.CreateSpyObj('Http', ['get']);
       randomService = new RandomService(<any> httpclientSpy);       
    });
    
        it('should return first, second, third', () => {
            spyOn(httpClientSpy, 'get').and.returnValue(Observable.of(mockResponse));
            // randomService. <your get method here...>
            randomService.getValue().subscribe((response) =>
                expect(resposne[0].length).toEqual(3);
    };
    });