我正在尝试测试angular2双向绑定以进行控制input.这是错误:
Can't bind to 'ngModel' since it isn't a known property of 'input'.
Run Code Online (Sandbox Code Playgroud)
app.component.html
<input id="name" type="text" [(ngModel)]="name" />
<div id="divName">{{name}}</div>
Run Code Online (Sandbox Code Playgroud)
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
name: string;
}
Run Code Online (Sandbox Code Playgroud)
app.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
describe('App: Cli', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
providers:[AppService]
});
});
it('divName', async(() => {
let …Run Code Online (Sandbox Code Playgroud) 在Angular 2中进行测试时,何时在TestBed中使用异步函数?
你什么时候用的?
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyModule],
schemas: [NO_ERRORS_SCHEMA],
});
});
Run Code Online (Sandbox Code Playgroud)
你何时使用它?
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyModule],
schemas: [NO_ERRORS_SCHEMA],
});
}));
Run Code Online (Sandbox Code Playgroud)
任何人都可以启发我吗?
unit-testing karma-jasmine angular2-testing angular angular-test
我是一个单元测试用于编辑对象的组件.该对象具有唯一性id,用于从服务中托管的对象数组中获取特定对象.具体id是通过路由传递的参数获得的,特别是通过ActivatedRoute类传递.
构造函数如下:
constructor(private _router:Router, private _curRoute:ActivatedRoute, private _session:Session) {
}
ngOnInit() {
this._curRoute.params.subscribe(params => {
this.userId = params['id'];
this.userObj = this._session.allUsers.filter(user => user.id.toString() === this.userId.toString())[0];
Run Code Online (Sandbox Code Playgroud)
我想对这个组件运行基本的单元测试.但是,我不确定如何注入id参数,组件需要此参数.
顺便说一下:我已经有了Session服务的模拟,所以不用担心.
我试图用angular 2 final测试我的组件,但是我得到一个错误,因为组件使用了该routerLink指令.我收到以下错误:
无法绑定到'routerLink',因为它不是'a'的已知属性.
这是ListComponent模板的相关代码
<a
*ngFor="let item of data.list"
class="box"
routerLink="/settings/{{collectionName}}/edit/{{item._id}}">
Run Code Online (Sandbox Code Playgroud)
这是我的考验.
import { TestBed } from '@angular/core/testing';
import { ListComponent } from './list.component';
import { defaultData, collectionName } from '../../config';
import { initialState } from '../../reducers/reducer';
const data = {
sort: initialState.sort,
list: [defaultData, defaultData],
};
describe(`${collectionName} ListComponent`, () => {
let fixture;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
ListComponent,
],
}).compileComponents(); // compile template and css;
fixture = TestBed.createComponent(ListComponent);
fixture.componentInstance.data = data;
fixture.detectChanges(); …Run Code Online (Sandbox Code Playgroud) 我一直在阅读用于单元测试的官方Angular2文档(https://angular.io/docs/ts/latest/guide/testing.html),但我正在努力设置组件的输入字段值,以便它反映在组件属性中(通过ngModel绑定).屏幕在浏览器中工作正常,但在单元测试中我似乎无法设置字段值.
我正在使用下面的代码."夹具"已正确初始化,因为其他测试工作正常."comp"是我的组件的实例,输入字段通过ngModel绑定到"user.username".
it('should update model...', async(() => {
let field: HTMLInputElement = fixture.debugElement.query(By.css('#user')).nativeElement;
field.value = 'someValue'
field.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(field.textContent).toBe('someValue');
expect(comp.user.username).toBe('someValue');
}));
Run Code Online (Sandbox Code Playgroud)
我的Angular2版本: "@angular/core": "2.0.0"
目前我重写提供者使用这样的模拟服务:
beforeEach(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
tcb.overrideProviders(AddFieldToObjectDropdownComponent,
[
provide(ServiceA, { useClass: MockServiceA })),
provide(ServiceB, { useClass: MockServiceB }))
])...
Run Code Online (Sandbox Code Playgroud)
我想对组件使用的管道做同样的事情.我试过了,provide(PipeA, { useClass: MockPipeA })和provide(PipeA, { useValue: new MockPipeA() })但都没有奏效.
我<router-outlet>在其他单元测试中遇到了丢失的消息,但是为了得到一个很好的隔离示例,我创建了一个AuthGuard,用于检查用户是否已登录以执行某些操作.
这是代码:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
现在我想为此编写一个单元测试.
这就是我开始测试的方式:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([
{
path: 'login',
component: DummyComponent
}
])
],
declarations: [
DummyComponent
],
providers: [
AuthGuardService,
{
provide: AuthService,
useClass: MockAuthService
}
]
});
});
Run Code Online (Sandbox Code Playgroud)
我创建了一个什么都不做的DummyComponent.现在我的考试.假设服务返回false并触发this.router.navigate(['/login']):
it('should not let users pass when not logged in', (): void => {
expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
});
Run Code Online (Sandbox Code Playgroud)
这将引发"无法找到要加载的主要插座"的异常.显然我可以使用toThrow()而不是toBe(false),但这似乎不是一个非常明智的解决方案.由于我在这里测试服务,因此没有模板可以放置<router-outlet>标签.我可以模拟路由器并创建自己的导航功能,但那么RouterTestingModule有什么意义呢?也许你甚至想检查导航是否有效.
如何使用karma和jasmine对Angular 2.0.0版中的路由器进行单元测试?
这是我的旧单元测试在版本2.0.0-beta.14中的样子
import {
it,
inject,
injectAsync,
beforeEach,
beforeEachProviders,
TestComponentBuilder
} from 'angular2/testing';
import { RootRouter } from 'angular2/src/router/router';
import { Location, RouteParams, Router, RouteRegistry, ROUTER_PRIMARY_COMPONENT } from 'angular2/router';
import { SpyLocation } from 'angular2/src/mock/location_mock';
import { provide } from 'angular2/core';
import { App } from './app';
describe('Router', () => {
let location, router;
beforeEachProviders(() => [
RouteRegistry,
provide(Location, {useClass: SpyLocation}),
provide(Router, {useClass: RootRouter}),
provide(ROUTER_PRIMARY_COMPONENT, {useValue: App})
]);
beforeEach(inject([Router, Location], (_router, _location) => {
router = _router;
location = …Run Code Online (Sandbox Code Playgroud)javascript karma-jasmine angular2-routing angular2-testing angular
我为我正在测试的组件创建了一个测试(spec)文件.但是当我运行测试时,它给出了一个错误说法
Cannot read property 'subscribe' of undefined
TypeError: Cannot read property 'subscribe' of undefined
at ComponentUndertest.ngOnInit
Run Code Online (Sandbox Code Playgroud)
这是显而易见的,因为我已经在ngOnInit()方法中订阅了某些内容,但是我可以在测试期间忽略订阅吗?或者我可以在测试期间伪造订阅吗?我已经搜索了很多关于这个问题但是找不到与angular2测试有关的任何内容.提前致谢.
鉴于以下代码,我尝试测试ngOnChangesAngular2 的生命周期钩子:
import {
it,
inject,
fdescribe,
beforeEachProviders,
} from '@angular/core/testing';
import {TestComponentBuilder} from '@angular/compiler/testing';
import {Component, OnChanges, Input} from '@angular/core';
@Component({
selector: 'test',
template: `<p>{{value}}</p>`,
})
export class TestComponent implements OnChanges {
@Input() value: string;
ngOnChanges(changes: {}): any {
// should be called
}
}
fdescribe('TestComponent', () => {
let tcb: TestComponentBuilder;
beforeEachProviders(() => [
TestComponentBuilder,
TestComponent,
]);
beforeEach(inject([TestComponentBuilder], _tcb => {
tcb = _tcb;
}));
it('should call ngOnChanges', done => {
tcb.createAsync(TestComponent).then(fixture => {
let testComponent: …Run Code Online (Sandbox Code Playgroud) angular ×10
angular2-testing ×10
unit-testing ×5
angular-cli ×1
angular-test ×1
javascript ×1
testing ×1
typescript ×1