2016-12-02 80 views
2

我正在尝试为Angular 2应用程序实现单元测试。但是我无法将它运用起来。 作为测试运行摩卡使用和执行这样的:用摩卡测试Angular 2服务

mocha -r ts-node/register -t 10000 ./**/*.unit.ts 

请看下面的测试文件,我定义了两个测试案例基本上应该做同样的事情,但没有一个是工作。

shared.service.unit.ts

import { TestBed, async, inject } from '@angular/core/testing'; 
import { SharedService } from './shared.service'; 
import * as Chai from 'chai'; 
import 'mocha'; 
const expect = Chai.expect; 

describe('SharedService',() => { 

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

    it('should be an object', 
     inject([SharedService], (service: SharedService) => { 
      expect(service).to.be.an('object'); 
     }) 
    ); 
}); 

describe('SharedService without the TestBed',() => { 
    let service: SharedService; 

    beforeEach(() => { 
     service = new SharedService(); 
    }); 

    it('should be an object',() => { 
     expect(service).to.be.an('object'); 
    }); 
}); 

第一种'SharedService'使用Angular Testing Utility。运行它给:

ReferenceError: Zone is not defined

第二个'SharedService without TestBed'不使用任何角度代码(类似于this example from Angular 2 Testing guide)。运行它给:

TypeError: Reflect.getMetadata is not a function

这些行添加到测试文件后:

import 'core-js/es6'; 
import 'core-js/es7/reflect'; 
import 'zone.js/dist/zone'; 

测试案例给出了同样的错误(从zone.js\dist\zone.js):

TypeError: Cannot read property 'prototype' of undefined

我在做什么错误?

回答

2

得到它,只需要import 'core-js/es7/reflect'

import 'core-js/es7/reflect'; 
import 'mocha'; 
import * as Chai from 'chai'; 
let expect = Chai.expect; 
import { SharedService } from './shared.service'; 

describe('SharedService',() => { 
    let service: SharedService; 

    beforeEach(() => { 
     service = new SharedService(); 
    }) 

    it('should be an object',() => { 
     expect(service).to.be.an('object'); 
    }) 
}); 
0

你需要加载所有的东西 - 角,ngzone,元数据,ES垫片等 - 静态的摩卡的 - 或者systemjs或者你使用设置此东西了 - 配置。