4

我正在尝试在带有 Jasmine 的 Angular 2 组件上运行 Angular 2 单元测试(我没有使用 Karma,但是......只是对我的代码进行 webpacking,然后在默认的 Jasmine SpecRunner.html 中运行测试)。

当我运行我的代码时,我收到错误消息:“已创建具有不同配置的平台。请先销毁它。” 一整天都在敲我的头。阅读我能找到的关于 StackOverflow 的每一篇文章,但我仍然卡住了。有什么建议么?

import { ComponentFixture, ComponentFixtureAutoDetect, TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from "@angular/platform-browser-dynamic/testing";

import {AppLogin} from "../../../app/login/app.login";

describe("Login Component", () => {
    let comp: AppLogin;
    let fixture: ComponentFixture<AppLogin>;
    let el: DebugElement;

    function setup() {
        TestBed.resetTestEnvironment();
        TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
    }
    setup();

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [AppLogin]
        });

        fixture = TestBed.createComponent(AppLogin);
        comp = fixture.componentInstance;
    });

    it("login form should pass validation", () => {
        fixture.detectChanges();

        var form = {
            EmailAddress: 'test@me.com',
            Password: 'test'
        };
        var validated = comp.formValidated(form);
        expect(validated).toBe(true);
    });
});

这是我正在尝试测试的组件...

import { Component } from '@angular/core';

@Component({
    selector: 'app-login',
    template: `
    <form *ngIf="active" (ngSubmit)="onSubmit()" class="form-signin">
        <h2 class="form-signin-heading">Please sign in</h2>

        <label for="EmailAddress" class="sr-only">Email address</label>
        <input type="email" name="EmailAddress" id="EmailAddress" class="form-control" placeholder="Email address"
               [(ngModel)]="form.EmailAddress" required autofocus>

        <label for="Password" class="sr-only">Password</label>
        <input type="password" name="Password" id="Password" class="form-control" placeholder="Password" required
               [(ngModel)]="form.Password">

        <div class="checkbox">
            <label>
                <input type="checkbox" id="RememberMe" value="remember-me" [(ngModel)]="form.RememberMe"> Remember me
            </label>
        </div>

        <div *ngIf="form.hasError">
            <div *ngFor="let error of form.errorMessages" class="alert alert-danger fade in">{{error.message}}</div>
        </div>

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
    `
})
export class AppLogin {
    form: any;

    constructor() {
        //
    }

    formValidated(form: any): boolean {
        form.errorMessages = [];
        form.hasError = false;

        if (form.EmailAddress == null)
            form.errorMessages.push({ message: 'Email Address is required.' });

        if (form.Password == null)
            form.errorMessages.push({ message: 'Password is required.' });

        if (form.errorMessages.count > 0)
            form.hasError = true;

        return !form.hasError;
    }

    onSubmit(form: any): void {
        console.log('Form data: ', form);
    }
}
4

1 回答 1

2

不幸的是,仅 Jasmine 并没有为我提供所需的调试信息,因此我不再单独使用 Jasmine 进行单元测试。我正在使用推荐的 Karma/Jasmine 设置。(注意:但是,我没有使用 Angular karma-test-shim,这就是我必须运行 TestBed.initTestEnvironment 的原因)。

我在 Karma 中运行了测试,但我收到了关于我的组件模板的错误。我的组件模板有一个角形。我必须将 angular FormsModule 导入我的测试环境。这是解决问题的代码...

import { ComponentFixture, ComponentFixtureAutoDetect, TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import { By, BrowserModule } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from "@angular/platform-browser-dynamic/testing";
import { FormsModule } from '@angular/forms';

import {AppLogin} from "../../../app/login/app.login";

describe("Login Component", () => {
    let comp: AppLogin;
    let fixture: ComponentFixture<AppLogin>;
    let el: DebugElement;

    beforeEach(() => {
        TestBed.resetTestEnvironment();
        TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());

        TestBed.configureTestingModule({
            imports: [ FormsModule, BrowserModule ],
            declarations: [ AppLogin ]
        });

        fixture = TestBed.createComponent(AppLogin);
        comp = fixture.componentInstance;
    });

    it("login form should pass validation", () => {
        fixture.detectChanges();

        var form = {
            EmailAddress: 'test@me.com',
            Password: 'test'
        };
        var validated = comp.formValidated(form);
        expect(validated).toBe(true);
    });
});

最初我在使用 Webpack 设置 Karma 时遇到了很多麻烦,但这是我编写的 Karma 配置,它对我来说非常有效(并且不需要 karma-test-shim)...

module.exports = function(config) {
    config.set({
        basePath: '',

        frameworks: ['jasmine'],

        files: [
            'src/tests/tests.ts',
            'src/tests/login/app.login.spec.ts'
        ],

        exclude: [
        ],

        preprocessors: {
            'src/tests/tests.ts': ['webpack'],
            'src/tests/login/app.login.spec.ts': ['webpack', 'sourcemap']
        },

        webpack: {
            devtool: 'inline-source-map',

            resolve: {
                extensions: ['', '.ts', '.js']
            },

            module: {
                loaders: [
                    {
                        test: /\.js$/,
                        loader: 'babel-loader',
                        query: {
                            presets: ['es2015']
                        }
                    },
                    {
                        test: /\.ts$/,
                        loaders: ['ts-loader']
                    }
                ]
            }
        },

        webpackMiddleware: {
            // webpack-dev-middleware configuration
            noInfo: true
        },

        plugins: [
            require("karma-webpack"),
            require("karma-jasmine"),
            require("karma-chrome-launcher"),
            require("karma-sourcemap-loader"),
            require("karma-spec-reporter")
        ],

        reporters: ['spec'],

        port: 9876,

        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true
    });
};

最后,这是我在 Karma 配置中包含的 tests.ts 文件的代码。这是我需要()运行角度测试所需的所有代码的地方......

require('zone.js/dist/zone');

require('reflect-metadata');
require('rxjs');

require('@angular/platform-browser');
require('@angular/platform-browser-dynamic');
require('@angular/core');
require('@angular/common');
require('@angular/http');
require('@angular/router');

Error.stackTraceLimit = Infinity;

require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy'); // since zone.js 0.6.15
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch'); // put here since zone.js 0.6.14
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');

var testing = require('@angular/core/testing');
于 2016-09-27T14:39:55.023 回答