如何在规格文件Angular Testing(Jasmin / karma)中注入服务

时间:2018-10-30 05:41:12

标签: javascript angular typescript karma-jasmine

我是新来编写Angular单元测试用例的人。我在控制器文件(.ts)中注入了一项服务。我将如何在规格文件中注入服务文件。

代码如下:

app.component.ts

getSortData() {
    this.sortService.sortNumberData(this.data, 'name', 'asce');
}

sort.service.ts

sortNumberData(data, rendererKey, type) {
    // data.sort((elem1, elem2) => {
    //   //if number is undefined, then assigning `MAX_SAFE_INTEGER` to to move it to the last in order. 
    //   if (elem1[rendererKey] == undefined) elem1[rendererKey] = Number.MAX_SAFE_INTEGER;
    //   if (!elem2[rendererKey] == undefined) elem2[rendererKey] = Number.MAX_SAFE_INTEGER;
    //   return Number(elem1[rendererKey]) - Number(elem2[rendererKey]);
    // });
    // if (type == "desc") {
    //   return data.reverse();
    // }
    // return data;   
    if (!Array.isArray(rendererKey)) {
        data.sort((elem1, elem2) => {
            if (elem1[rendererKey] == undefined && elem2[rendererKey] == undefined) {
                return 0;
            } else if (elem1[rendererKey] == undefined) {
                return 1;
            } else if (elem2[rendererKey] == undefined) {
                return -1;
            } else {
                return elem1[rendererKey] - elem2[rendererKey];
            }
        });
        // if the type of rendererKey is array, then use array elements as keys hierarchally.
        // This is used when compare element is not direct property of each element of data array.
    } else if (Array.isArray(rendererKey)) {
        data.sort((elem1, elem2) => {
            let temp1 = elem1, temp2 = elem2;
            rendererKey.map((e) => { temp1 = temp1[e], temp2 = temp2[e] });
            console.log(temp1, temp2);
            if (temp1 == undefined && temp2 == undefined) {
                return Number.MAX_SAFE_INTEGER - Number.MAX_SAFE_INTEGER
            } else if (temp1 == undefined) {
                return Number.MAX_SAFE_INTEGER - temp2;
            } else if (temp2 == undefined) {
                return temp1 - Number.MAX_SAFE_INTEGER;
            } else {
                return temp1 - temp2;
            };
        })

    }
    if (type == "desc") {
        return data.reverse();
    }
    return data;
}

我们不知道。如何在规格文件中注入此服务。谁能帮助我们?

谢谢!

3 个答案:

答案 0 :(得分:3)

您要实现的实际上是集成测试,因为您要同时测试两个单元(AppComponentSortService)。

由于您正在谈论单元测试,所以我认为您想测试AppComponent类。这意味着AppComponent中使用的任何可注入依赖项都必须被模拟。您的情况是SortService类。有两种方法可以实现。

  

方法1:对SortService使用Mock类。

     

app.component.spec.ts

// Mock the SortService class, its method and return it with mock data
class MockSortService extends SortService{
                getSortData(data, rendererKey, type) {
                    return [someRandomArray];
                }
}

beforeEach(async( () => {
    TestBed.configureTestingModule({
            providers: [                   
                // Use the power of Angular DI with following provider. This will replace SortService with MockSortService in injector
                { provide: SortService, useClass: MockSortService },
            ]
    });
));
  

方法2:使用间谍对象。

     

app.component.spec.ts

beforeEach(async( () => {
        // Create jasmine spy object 
        sortServiceSpy = jasmine.createSpyObj('SortService', 'sortNumberData');
        // Provide the dummy/mock data to sortNumberData method.
        sortServiceSpy.sortNumberData.returnValue([someRandomArray]);
        TestBed.configureTestingModule({
                providers: [                   
                    { provide: SortService, useValue: sortServiceSpy},
                ]
        });
    ));

我喜欢方法2。它小巧而优雅。但是您可以使用两种方法中的任何一种。

希望这会有所帮助!

答案 1 :(得分:2)

要将服务注入到规范文件中,您必须添加TestBed配置并在与模块ts文件相同的提供程序数组中注册服务。

示例:-describe('测试用例的描述',()=> { const sortService;

   beforeEach(async( () => {
     TestBed.configureTestingModule({
         declarations: [],    
         providers: [SortService]
      }).compileComponents();
   }));

   beforeEach( () => {
       sortService = TestBed.get(SortService);
   });

答案 2 :(得分:0)

此答案假设您要对组件进行单元测试。

如果使用Angular TestBed测试组件,则可以通过在providers数组中指定它来为您进行服务注入。假设您要测试组件(并仅模拟服务),我将执行以下操作:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SortService } from '../services/sort.service';
import { AppComponent } from './app.component';

describe('app component', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;
    let spySortService = jasmine.createSpyObj({ sortNumberData: null });

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [/* add all needed imports for AppComponent */],
            declarations: [ AppComponent ],
            providers: [
                { provide: SortService, useValue: spySortService }
            ]
        });
        fixture = TestBed.createComponent(AppComponent);
  }));

    it('should create', () => {
        expect(fixture).toBeTruthy();
    });
    it('getSortData() should call SortService sortNumberData() method', () => {
        fixture.detectChanges();
        component.getSortData();
        expect(spySortService.sortNumberData.toHaveBeenCalled();
    });
});