我正在尝试在带有 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);
}
}