如何用Mocha测试Angular 2?

Xer*_*ati 7 unit-testing mocha.js systemjs angular

几天来我一直在反对这个问题,而且无法到达任何地方......我正在尝试使用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();
    });
});
Run Code Online (Sandbox Code Playgroud)

我可以告诉他,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();
    });
});
Run Code Online (Sandbox Code Playgroud)

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

tom*_*jan -4

我认为 mocha 不能直接使用,因为它仅在节点上运行(当您仅在服务器端渲染 HTML 字符串时,也许可以使用 Angular2 通用)。话虽这么说,您可以使用mochify,它是 mocha,并在后台使用 browserify。我正在为该设置开发一个示例项目。

然后测试看起来像这样:

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

});
Run Code Online (Sandbox Code Playgroud)