Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular2提供程序自动模拟每个提供程序中的方法_Angular_Unit Testing - Fatal编程技术网

Angular2提供程序自动模拟每个提供程序中的方法

Angular2提供程序自动模拟每个提供程序中的方法,angular,unit-testing,Angular,Unit Testing,我有一个angular2组件,它依赖于许多提供者。从我到目前为止阅读的内容来看,为了模仿提供者,我有两个选择 为每个提供者编写一个模拟服务 仅使用spy和mock组件调用的方法 如果我选择了选项1,那么我必须编写大量的伪代码,这是对空间的浪费。如果我写下选项2,那么我需要对每个提供者都有复杂的了解,然后只编写mock方法。我想做的是在所有提供程序中自动模拟所有方法,然后仅在需要时编写spies(自定义模拟逻辑)。我该怎么做 例如,如何自动模拟以下服务 public class ActualSer

我有一个angular2组件,它依赖于许多提供者。从我到目前为止阅读的内容来看,为了模仿提供者,我有两个选择

  • 为每个提供者编写一个模拟服务
  • 仅使用spy和mock组件调用的方法
  • 如果我选择了选项1,那么我必须编写大量的伪代码,这是对空间的浪费。如果我写下选项2,那么我需要对每个提供者都有复杂的了解,然后只编写mock方法。我想做的是在所有提供程序中自动模拟所有方法,然后仅在需要时编写spies(自定义模拟逻辑)。我该怎么做

    例如,如何自动模拟以下服务

    public class ActualService(){
      public getUsers(){
         //Actual call
      }
    
      public udpateUser(user:User){
         //Actual call to be backend to update the user
      }
    }  
    

    我如何使用像Sinon这样的库自动地模仿这里面的一切而不做任何事情?在单元测试中,快捷方式是不可接受的,因为这会导致低质量的测试,在应该失败时不会失败,在失败时很难调试

    更好的方法是创建一个新的存根/模拟对象,该对象只包含受当前测试影响的方法。当测试代码被更改为引入测试中未考虑的方法时,这将导致测试失败,并显示清晰的错误消息

    尽管有上述缺点,但Sinon仍有可能做到这一点:

    const serviceStub = sinon.createStubInstance(Service);
    
    或者用茉莉花:

    const serviceStub = jasmine.createSpyObj('Service',
      Service.prototype.getOwnPropertyNames
      .filter(prop => typeof Service.prototype[prop] === 'function')
    );
    
    ...
    providers: [{ provide: Service, useValue: serviceStub }]
    ...