【问题标题】:Jasmine/Karma test services with params带参数的 Jasmine/Karma 测试服务
【发布时间】:2017-12-14 01:36:58
【问题描述】:

我想使用 Jasmine 和 Karma 测试使用 TestBed 或 SpyOn 的服务依赖项。但我在 Angular 网站上没有找到任何示例:https://angular.io/guide/testing

我该怎么做?

【问题讨论】:

    标签: angular karma-jasmine


    【解决方案1】:

    这是一个关于如何开始使用测试服务的最小示例。在大多数情况下,您不需要使用 TestBed,所以我在这个最小的单元测试示例中省略了它:

    Abc 服务:

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class AbcService {
    
      constructor(private otherService) {
      }
    
      add(x: number, y: number) {
        return x + y;
      }
    
      submit(x) {
        this.otherService.submit(x);
      }
    
    }
    

    Abc 服务规范文件:

    import { AbcService } from './abc';
    
    
    describe('AbcService', () => {
    
      it('should add 1 + 2', () => {
        // Arrange
        const sut = new AbcService(null);
    
        // Act
        const result = sut.add(1, 2);
    
        // Assert
        expect(result).toEqual(3);
      });
    
      it('should dispatch SET_INTERACTION when setAnswer is run', () => {
    
        // Arrange
        const mockOtherService = jasmine.createSpyObj('mockOtherService', ['submit']);
        const sut = new AbcService(mockOtherService);
    
        // Act
        sut.submit(10);
    
        // Assert
        expect(mockOtherService.submit).toHaveBeenCalledWith(10);
      });
    });
    

    【讨论】:

    • 太棒了,谢谢
    【解决方案2】:
    describe('Test Service', () => {
        let yourCurrentService: YouCurrentService;
        let yourServiceDependencyService : YourServiceDependencyService;
    
        beforeEach(() => {
    
          let injector = ReflectiveInjector.resolveAndCreate([
            YouCurrentService,
            YourServiceDependencyService
          ]);
          yourCurrentService = injector.get(YourServiceDependencyService);
          yourCurrentService = injector.get(YouCurrentService);
        });
    
        it('test', () => {
    
        });  
    });
    

    【讨论】:

      猜你喜欢
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 2018-07-07
      • 2020-08-12
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      相关资源
      最近更新 更多