Testing Angular 2 service with mocha

2019-03-31 12:48发布

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');
    });
});

The first one 'SharedService' uses the Angular Testing Utility. Running it gives:

ReferenceError: Zone is not defined

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 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';

Both test cases give the same error (from zone.js\dist\zone.js):

TypeError: Cannot read property 'prototype' of undefined

What am I doing wrong?

2条回答
欢心
2楼-- · 2019-03-31 13:11

Got it, just needed to 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');
    })
});
查看更多
狗以群分
3楼-- · 2019-03-31 13:12

You need to load all that stuff - angular, ngzone, metadata, es shims, etc. - statically in the mocha's - or systemjs or whatever you use for setting this stuff up - configuration.

查看更多
登录 后发表回答