标签: angular2-testing

在angular2,依赖注入中进行单元测试

花费时间与角度1后开始角度为2.没有单元测试这么多,因为它更像是一个侧面项目的东西,我尝试至少开始OK ...我开始使用AngularClass中的示例,如果这样做的话区别.

app.component.ts已经挣扎,其中包含我的导航位.这里模板的相关位:

<nav class="navbar navbar-light bg-faded">
  <div class="container">
    <div class="nav navbar-nav">
      <a class="navbar-brand" [routerLink]=" ['./'] ">Navbar</a>
      <loading class="nav-item nav-link pull-xs-right" [visible]="user === null"></loading>
  </div>
</div>
</nav>

<div class="container">
  <main>
    <router-outlet></router-outlet>
</main>
</div>

<footer>
  <hr>
  <div class="container">

</div>
</footer> 
Run Code Online (Sandbox Code Playgroud)

组件本身并不多:

import { Component, ViewEncapsulation } from '@angular/core';
import { AuthService } from './_services';
import { User } from './_models';
import { Loading } from './_components';

@Component({
    selector: 'app',
    encapsulation: ViewEncapsulation.None,
    template: require('./app.component.html'),
    styles: [
        require('./app.style.css')
    ]
}) …
Run Code Online (Sandbox Code Playgroud)

unit-testing angular2-testing angular

10
推荐指数
1
解决办法
4267
查看次数

在angular2中测试router-outlet组件

我有一个html所在的homecomponent

//home.component.html

<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

//home.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { HomeService} from './shared/services/home.service';

@Component({
  // moduleId: module.id,
  selector: 'app-home',
  templateUrl: 'home.component.html',
  styleUrls: ['home.component.css'],
  providers:[HomeService]
})
export class HomeComponent implements OnInit {

  constructor(private service:HomeService , private route:Router) { }

  ngOnInit() {
    if(this.service.isAuthenticated()){
      this.route.navigateByUrl('dashboard/main');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

//home.component.spec.ts

import { ComponentFixture, TestBed  } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';
import { async, inject } from …
Run Code Online (Sandbox Code Playgroud)

angular2-routing angular2-testing angular

10
推荐指数
1
解决办法
5832
查看次数

单元测试带有导入模块的angular2组件

我试图在使用angular-material2的组件上编写测试,但是当我将它添加到我的testModule声明时,我得到:

Error: Template parse errors:
    'md-card-title' is not a known element:
    1. If 'md-card-title' is an Angular component, then verify that it is part of this module.
    2. If 'md-card-title' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
Run Code Online (Sandbox Code Playgroud)

将MaterialModule添加到声明中会抛出`错误:模块声明的意外模块'MaterialModule'

config/spec-bundle.js中的DynamicTestModule'(第24994行)

这是我的spec文件的样子:

  beforeEach(() => TestBed.configureTestingModule({
    declarations: [],
    providers: [
      { provide: DataService, useValue: mockDataService },
      { provide: ActivatedRoute, useClass: MockActivatedRoute },
      { provide: Router, useValue: mockRouter },
      CellViewComponent
    ]
  }));
Run Code Online (Sandbox Code Playgroud)

添加CellViewComponent …

typescript karma-jasmine angular2-testing angular-material2 angular

10
推荐指数
2
解决办法
1万
查看次数

如何在测试中模拟NavParams?

这可能只是一个Ionic 2问题,因为我没有在Angular 2文档中看到NavParams,但是有些概念可能会翻译,所以我标记了两者.

鉴于我navparams.get('somekey')为了侦听传入的参数而调用,在测试中模拟NavParams是很棘手的.

例如,以下是我目前的工作方式:

export class NavParamsMock {
  public get(key): any {
    return String(key) + 'Output';
  }
}
Run Code Online (Sandbox Code Playgroud)

这适用于真正的基本测试,但如果我有一个组件,我必须测试它gets是一种特定类型Object,例如a User.

然后,我可以做类似的事情

export class NavParamsMock {
  public get(key): any {
    if (key === 'user') {
       return new User({'name':'Bob'})
    }
    return String(key) + 'Output';
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您想get(user)在另一个测试中使用,或者甚至是另一个组件的规范,则这不起作用.假设您在两个不同的组件中使用NavParams,并且当您这样做时它们都期望不同的结果get(user),模拟变得越来越棘手.

有没有人找到这种情况的解决方案?

unit-testing ionic2 angular2-testing angular

10
推荐指数
2
解决办法
3400
查看次数

Angular2组件:测试表单输入值更改

我有一个文本输入,我正在听取更改.

mycomponent.ts

ngOnInit() {
    this.searchInput = new Control();
    this.searchInput.valueChanges
        .distinctUntilChanged()
        .subscribe(newValue => this.search(newValue))
}
search(query) {
    // do something to search
}
Run Code Online (Sandbox Code Playgroud)

mycomponent.html

<search-box>
    <input type="text" [ngFormControl]="searchInput" >
</search-box>
Run Code Online (Sandbox Code Playgroud)

运行应用程序一切正常,但我想对其进行单元测试.

所以这就是我的尝试

mycomponent.spec.ts

beforeEach(done => {
    createComponent().then(fix => {
        cmpFixture = fix
        mockResponse()
        instance = cmpFixture.componentInstance
        cmpFixture.detectChanges();
        done();
    })
})
describe('on searching on the list', () => {
        let compiled, input
        beforeEach(() => {
            cmpFixture.detectChanges();
            compiled = cmpFixture.debugElement.nativeElement;
            spyOn(instance, 'search').and.callThrough()
            input = compiled.querySelector('search-box > input')
            input.value = 'fake-search-query'
            cmpFixture.detectChanges();
        })
        it('should …
Run Code Online (Sandbox Code Playgroud)

unit-testing angular2-forms angular2-testing angular2-components angular

9
推荐指数
1
解决办法
9444
查看次数

如何在Angular2中使用MockBackend对Http post,put,delete进行单元测试?

所以我正在测试我的angular2组件和服务.

到目前为止,我已经使用mockBackend来模拟get request in service,如下所示:

/* tslint:disable:no-unused-variable */

import { MockBackend } from '@angular/http/testing';
import { Http, ConnectionBackend, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { PagesService } from './pages.service';
import { tick, fakeAsync } from '@angular/core/testing/fake_async';
import { inject, TestBed } from '@angular/core/testing/test_bed';
import {GlobalService} from './../../shared/global.service';

describe('PagesService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        {
          provide: Http, useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => {
            return new Http(backend, defaultOptions);
          }, deps: [MockBackend, BaseRequestOptions]
        },
        { provide: PagesService, …
Run Code Online (Sandbox Code Playgroud)

typescript karma-jasmine angular2-testing angular

9
推荐指数
1
解决办法
4218
查看次数

如何模拟angular2 platform-b​​rowser标题组件以进行测试

我正在使用Jasmine编写Angular 2组件的单元测试.我想测试在我的组件实例化时我的文档标题是否已设置为特定值.

这是我的组件

import { Component } from '@angular/core';
import { Title }     from '@angular/platform-browser';

@Component({
  selector: 'cx-account',
  templateUrl: 'app/account/account.component.html',
})
export class AccountComponent {
  public constructor(private titleService: Title ) {
    titleService.setTitle("Account");
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我为测试而编写的,但它不起作用.titleService.getTitle()给了我Karma调试跑步者页面标题.

import { TestBed }      from '@angular/core/testing';
import { Title, By }           from '@angular/platform-browser';
import { AccountComponent } from './account.component';

describe('AppComponent Tests', function () {
  let titleService: Title = new Title(); 
  beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [AccountComponent],
        providers:    [ {provide: Title } ],      
    }); …
Run Code Online (Sandbox Code Playgroud)

karma-jasmine angular2-testing angular

9
推荐指数
1
解决办法
2695
查看次数

Angular2如何单元测试自定义验证器指令?

我为输入字段写了一个非常简单的自定义验证器:

import { Directive } from '@angular/core';
import { AbstractControl, NG_VALIDATORS } from '@angular/forms';

function numberValidator(c: AbstractControl) {
    if (!c.value) return null;
    return new RegExp('^[1-9][0-9]{6,9}$').test(c.value) ? null : {
        validateNumber: {
            valid: false
        }
    }
}

@Directive({
    selector: '[number-validator]',
    providers: [
        { provide: NG_VALIDATORS, multi: true, useValue: numberValidator }
    ]
})
export class NumberValidator {

}
Run Code Online (Sandbox Code Playgroud)

我想对这个验证器进行单元测试.我在Angular2页面上阅读了测试属性指令,但没有更改的css或html.我该如何对这个验证器进行单元测试?

unit-testing karma-jasmine angular2-forms angular2-testing angular

8
推荐指数
1
解决办法
9893
查看次数

spyOn无法找到一个窥探start()的对象

我正在使用angular-cli测试框架.

在我的组件中,我使用了'ng2-slim-loading-bar'节点模块.

submit(){
    this._slimLoadingBarService.start(() => {
    });
    //method operations
}
Run Code Online (Sandbox Code Playgroud)

现在当我测试这个组件时,我已经将spyOn这个服务应用于:

beforeEach(() => {
    let slimLoadingBarService=new SlimLoadingBarService();
    demoComponent = new DemoComponent(slimLoadingBarService);
    TestBed.configureTestingModule({
        declarations: [
            DemoComponent
        ],
        providers: [
            { provide: SlimLoadingBarService, useClass: SlimLoadingBarService}
        ],
        imports: [
            SharedModule
        ]
    });
});
it('should pass data to servie', () => {
    spyOn(slimLoadingBarService,'start').and.callThrough();
   //testing code,if I remove the above service from my component, test runs fine
});
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

它抛出以下错误:

spyOn无法找到一个窥探start()的对象

javascript jasmine typescript angular2-testing angular

8
推荐指数
2
解决办法
2万
查看次数

Angular2 - 在不同环境中执行e2e测试

我是新来的Protractor.我开发了几个测试用例来完成端到端测试.这些测试案例工程,我们有所有3个不同的环境罚款:dev,testingproduction.

但是我需要在测试用例中更改Angular应用程序URL,以确定需要进行测试的环境(因为URL因环境而异).

我正在使用Angular CLI命令ng e2e来运行测试.现在我的问题是

1)是否可以传递参数ng e2e,以便基于参数,可以在测试用例内动态设置URL?

2)是否有必要protractor全局安装,因为Angular CLI使用protractorunder node_modules?创建角度应用程序?

在我的项目设置中,Protractor版本是5.1.2,Angular CLI版本是1.2.0.

以下是Protract配置

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
     './e2e/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome'
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  useAllAngular2AppRoots: true,
  beforeLaunch: function() {
    require('ts-node').register({
        project: 'e2e'
    });
  },
  onPrepare: function() {
    jasmine.getEnv().addReporter(new …
Run Code Online (Sandbox Code Playgroud)

protractor angular2-testing angular2-cli angular

8
推荐指数
1
解决办法
3220
查看次数