如何用Mocha测试Angular 2?

时间:2016-01-16 16:05:25

标签: angular unit-testing mocha systemjs

我已经对这个问题猛烈抨击了几天,而且无法到达任何地方......我正在尝试使用Mocha来测试我的Angular 2应用程序(如果重要的话,基于SystemJS),我只是无法弄清楚如何获取控制器的实例。

我正在尝试我能提出的最简单的案例;

import {bootstrap} from 'angular2/platform/browser';
import {App} from '../app/app';
import {Type} from 'angular2/core';

describe('Login', () => {
    let app:App;

    beforeEach((done) => {
        console.log(bootstrap);
        bootstrap(<Type>App)
            .then(result => result.instance)
            .then(instance => {
                app = instance;
                done();
            });
    });

    it('Test for App to Exist', (done) => {
        console.log(app);
        done();
    });
});

尽管我可以说,console.log(bootstrap)以某种方式失败了,因为我的gulp-mocha任务刚刚死亡(默默地)。注释掉bootstrap引用只做一个虚拟测试;

import {bootstrap} from 'angular2/platform/browser';
import {App} from '../app/app';
import {Type} from 'angular2/core';

describe('Login', () => {
    let app:App;

    beforeEach((done) => {
        done();
    });

    it('Test for App to Exist', (done) => {
        console.log(app);
        done();
    });
});

按照我的预期记录undefined。有没有人设法得到这样的东西工作?这里的目标是单元测试控制器,所以我正在努力避免使用phantomJS / webdriver /等。

1 个答案:

答案 0 :(得分:-4)

我认为mocha不能直接使用,因为它只在节点上运行(当你只渲染HTML字符串服务器端时,可能会使用Angular2通用)。话虽这么说,你可以使用mochify mocha与后台使用的browserify。我正在为example project进行设置。

测试然后可以看起来像这样:

// import everything needed for to run Angular (we're running in PhantomJS by defualt but other browsers are possible too)
import "es6-shim";
import "es6-promise";
import "zone.js";
import "rxjs";
import "reflect-metadata";

import "../../typings/browser.d.ts";

import {Injector, enableProdMode} from "angular2/core";
import {HTTP_PROVIDERS} from "angular2/http";


// import stuff we need to instantiate component
import GithubComponent from "./gihub-component";
import GithubService from "./github-service";
import Config from "../config";

import * as sinon from "sinon";

enableProdMode();

describe("github-component", () => {

    let injector: Injector;
    let component: any;
    let service: any;

    beforeEach(() => {
        // instantiate Angular 2 DI context
        injector = Injector.resolveAndCreate([
            HTTP_PROVIDERS,
            GithubComponent,
            GithubService,
            Config
        ]);
        component = injector.get(GithubComponent);
        service = injector.get(GithubService);
        sinon.spy(service, "getRepos");
    });

    afterEach(() => {
        service.getRepos.restore();
    });

    it("searches for repository", () => {
        component.query.updateValue("test");

        return setTimeout(() => {
            sinon.assert.calledOnce(service.getRepos);
            sinon.assert.calledWith(service.getRepos, "test");
        }, 300);
    });

});