2016-12-02 103 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或者你使用設置此東西了 - 配置。