微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angularjs – 如何用Mocha测试Angular 2?

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

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

我认为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);
    });

});

原文地址:https://www.jb51.cc/angularjs/141043.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐