使用Mocha测试Angular 2服务 [英] Testing Angular 2 service with mocha
问题描述
我正在尝试为Angular 2应用实施单元测试.但是我无法使其正常工作. 作为测试运行器 mocha 的使用和执行方式如下:
I am trying to implement unit tests for an Angular 2 app. But I can't get it it to work. As test runner mocha is used and executed like this:
mocha -r ts-node/register -t 10000 ./**/*.unit.ts
请考虑以下测试文件,其中定义了两个测试用例,它们基本上应该做相同的事情,但没有一个起作用.
Consider the following test file where I define two test cases which basically should do the same thing, but neither one is working.
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'
使用角度测试实用程序.运行它可以得到:
The first one 'SharedService'
uses the Angular Testing Utility. Running it gives:
ReferenceError:未定义区域
ReferenceError: Zone is not defined
第二个'SharedService without TestBed'
不使用任何Angular代码(类似于
The second one 'SharedService without TestBed'
does not use any Angular code (similar to this example from Angular 2 Testing guide). Running it gives:
TypeError:Reflect.getMetadata不是函数
TypeError: Reflect.getMetadata is not a function
将以下行添加到测试文件后:
After adding these lines to the test file:
import 'core-js/es6';
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';
两个测试用例都给出相同的错误(来自zone.js\dist\zone.js
):
Both test cases give the same error (from zone.js\dist\zone.js
):
TypeError:无法读取未定义的属性"prototype"
TypeError: Cannot read property 'prototype' of undefined
我在做什么错了?
推荐答案
知道了,只需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');
})
});
这篇关于使用Mocha测试Angular 2服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!