![](/img/trans.png)
[英]How to test Angular2 pipe in nodejs with mocha without karma
[英]How does one test Angular 2 with Mocha?
幾天來我一直在反對這個問題,而且無法到達任何地方......我正在嘗試使用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 /等。
我認為mocha不能直接使用,因為它只在節點上運行(當你只渲染HTML字符串服務器端時,可能會使用Angular2通用)。 話雖這么說,你可以使用mochaify ,它是mochaify與后台使用的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);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.