角度2单位测试

时间:2016-05-09 05:37:19

标签: unit-testing angular jasmine

使用Jasmine进行单元测试时遇到了一些问题。第一个:

我需要在一个名为CaseList的组件中测试它:

gotoDetail(case: Case){
  this._router.navigate(['CaseDetail', {"id": case.id}]);
}

我在测试中的所有尝试都给出了错误。这是未定义的,因为我没有在我的测试中定义它,因为我无法弄清楚如何!我甚至没有在测试中提出任何好的尝试,因为我不知道如何继续。所以这就是为什么我没有在这里发布任何尝试...

编辑:路由器测试中与上述问题相关的部分,但我在一个单独的文件中测试所有路由!这个测试有效!

it('Should navigate to Case Detail List', (done) => {   
router.navigate(['CaseDetail', {id: 'test'}]).then(() => {
        expect(location.path()).toEqual('/casedetail/test');
        done();
    }).catch(e => done.fail(e));
});

来自详细信息组件的第二次测试(在选择案例后导航用户):

addStep(){
  this.case.getSteps().push(new Step());
}

我还有一个需要测试的删除方法:

removeStep(step: Step){
  this.case.removeStep(step);
}

此组件的构造函数:

constructor(public _routeParams: RouteParams, public _service: Service) {
  this.case = _service.getById(_routeParams.get('id'));
}

所以我尝试为add-method做的测试:

it('passes new step to case-class', () => {
  spyOn(case, 'addStep')
  .and.returnValue(Observable.of({complete: true}))
  caseDetail.addStep();
  expect(case.addStep).toHaveBeenCalledWith(step);
});

因此,这些方法调用名为“Case”的单独类中的方法。

我在测试这些时遇到的错误就是这种情况是空的。我想路由和服务会混淆它,就像在同一个组件中我有其他“相同”的方法,并测试这些工作正常。但他们属于不同的阶层。

同一组件中的方法,指的是“步骤” - 类:

addFeedback(step: Step){
  step.addFeedback(new Feedback());
}

测试完美无缺:

it('passes feedback value to Step class', () => {
  spyOn(step, 'addFeedback')
  .and.returnValue(Observable.of({complete: true}))
  caseDetail.addFeedback(step);
  expect(step.addFeedback).toHaveBeenCalledWith(feedback);
})

因此,在测试组件时,我应该已经定义了所需的所有内容,因为反馈方法的测试可行。我只需要以某种方式定义“case”对象,这样它就不会抱怨它为null。

希望你能解决我的问题,希望你能提供帮助! :)

1 个答案:

答案 0 :(得分:1)

为了使您的测试用例正常工作,您必须在测试之前添加路由器和案例作为提供者。

路由示例:

import {RootRouter} from 'angular2/src/router/router';
import {Location, RouteParams, Router, RouteRegistry, ROUTER_PRIMARY_COMPONENT} from 'angular2/router';
import {SpyLocation} from 'angular2/src/mock/location_mock';
import {provide} from 'angular2/core';

describe('Router', () => {
  let location, router;

  beforeEachProviders(() => [
    RouteRegistry,
    provide(Location, {useClass: SpyLocation}),
    provide(Router, {useClass: RootRouter}),
    provide(ROUTER_PRIMARY_COMPONENT, {useValue: App}),
  ]);

  beforeEach(inject([Router, Location], (_router, _location) => {
    router = _router;
    location = _location;
  }));

  it('Should be able to navigate to Home', done => {
    router.navigate(['Index']).then(() => {
      expect(location.path()).toBe('');
      done();
    }).catch(e => done.fail(e));
  });
});

案例提供者:

  import {Case} from '../case';

  beforeEachProviders(() => [
    provide(case, Case)
  ]);
相关问题