标签: angular-test

在 Angular 2 茉莉花中使用 ngif 异步调用对 html 元素进行单元测试

我正在为有条件的 html div 编写单元测试*ngIf

<div *ngIf="clientSearchResults$ | async  as searchResults" class = 'fgf'  #datalist id="mydata" >
  <app-client-list id="clientDataTable1" class="clientDataTable dataTable" [clients]='searchResults'></app-client-list>
</div>
Run Code Online (Sandbox Code Playgroud)

当我从ngrx存储收到数据时,这个ngIf条件成立。下面是填充此数据的组件代码。

searchData(client: Client) {
      //// some conditions
      this._clientService.getClientList()
     .subscribe(data => {
      const filteredData = this.filterData(data, client);
      this.isDataFound = filteredData !== null && filteredData.length > 0;
      this.testbool = true;
      /// In this line, my div got the data and using async condition, we 
      /// fill the div element.
      this.store.dispatch(new SetClientSearchResultsAction(filteredData));

    });
}
Run Code Online (Sandbox Code Playgroud)

现在,在为此编写单元测试用例时。

it('should …
Run Code Online (Sandbox Code Playgroud)

typescript karma-jasmine ngrx angular angular-test

6
推荐指数
2
解决办法
4931
查看次数

Angular jasmine 测试无法触发使用 fromEvent rxjs 运算符创建的 Observable

我有一个简单的案例。AppComponentAngular 应用程序的标准包含ChildComponent在其自己的模块中定义的ChildModule

的模板ChildComponent很简单

<div class="child" (click)="testClick($event)"></div>
Run Code Online (Sandbox Code Playgroud)

ChildComponent有一个更简单的testClick(event)方法,它只在控制台上记录一条消息。

testClick(event) {
    console.log(event);
}
Run Code Online (Sandbox Code Playgroud)

现在我想建立一个AppComponent模拟点击的测试ChildComponent

这是测试的代码

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let app: AppComponent;
  let child: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ChildModule ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    app = fixture.debugElement.componentInstance;
    child = fixture.debugElement.query(By.css('.child'));
    fixture.detectChanges();
  });

  it(`should create the child'`, async(() => {
    expect(child).toBeTruthy();
  }));

  it(`clicks on …
Run Code Online (Sandbox Code Playgroud)

jasmine rxjs angular angular-test

6
推荐指数
1
解决办法
2218
查看次数

ng 测试给出组件应该创建

我已经用 编写了我的第一个角度应用程序Angular 6

我还没有编写任何测试,但在生成components和时自动创建了一些默认测试文件services

当我使用运行自动生成的测试时

ng test
Run Code Online (Sandbox Code Playgroud)

它给出了太多的错误。其中一个错误就像

ChangeAvatarModalComponent should create

Failed: Template parse errors:
There is no directive with "exportAs" set to "ngForm" ("
<div class="modal-body">

  <form [formGroup]="changeAvatarForm" id="avatar-form" [ERROR ->]#formDir="ngForm" (submit)="onSubmit()">
  <div class="row">
    <div class="col-md-12">
"): ng:///DynamicTestModule/ChangeAvatarModalComponent.html@8:56
Can't bind to 'formGroup' since it isn't a known property of 'form'. ("
<div class="modal-body">
Run Code Online (Sandbox Code Playgroud)

我有一个帐户模块,其中包含ChangeAvatarModalComponent

我在account.module.ts中有以下几行

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forChild(AccountRoutes),
    NgbModule
  ],
  declarations: [
    ChangeAvatarModalComponent
  ], …
Run Code Online (Sandbox Code Playgroud)

angular angular-test angular6

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

如何在包含异步逻辑的 Angular 组件中测试 Observable 是否不发出

假设我有一个 Angular 组件,它定义了一个 ObservablemyObs$作为其属性之一。

在一项测试中,给定某些条件,我想测试myObs$不通知。在逻辑上有一些延迟,所以测试必须是异步的。

我正在使用茉莉花

到目前为止,我已经能够制定这个解决方案:

it('async test', done => {
    let dataEmitted;
    myObs$
    .pipe(
      tap(data => dataEmitted = data),
    )
    .subscribe();
    setTimeout(() => {
      if (dataEmitted) {
        done.fail('should not emit');
      } else {
        done();
      }
    }, 1000);
  });
Run Code Online (Sandbox Code Playgroud)

但我对此并不满意。我必须依靠setTimeout执行检查和调用done函数。

有关如何正确执行此类测试的任何建议?同步解决方案不起作用,因为逻辑中存在内在的异步性。

jasmine rxjs angular angular-test

6
推荐指数
1
解决办法
2400
查看次数

Angular 7 测试 - 异步函数调用 + async..await

在 Angular 7 单元测试中,有没有办法async( async(){} )在将异步支持与async..await关键字结合使用时避免双重语法?

我是 angular 的新手,但我是一位经验丰富的程序员,而且我无法选择我喜欢的测试风格。

我想async..await在测试中安全使用,并且我理解以下语法。然而,当指导开发人员接触现代 javascript 和/或async..await双重async(async())语法的概念时,对他们来说是多余的和令人困惑的。他们忽略了外部异步。服务中抛出的异常会导致在实际测试之外报告失败,这很难追踪。

似乎以下之一会更好:

  1. it()应该神奇地支持async..await和包装我的回调,async()这样我就不必考虑它了。
  2. it()应该采用一个可选的函数参数(即,asyncor fakeAsync)来包装我的回调。
  3. it()变化ita()并且itfa()应该存在,它将用适当的异步助手包装我的回调。
  4. it()用 包装我的回调async,另外一个itf()将我的回调包装在fakeAsync.

我是否缺少现有的概念或语法?有更好的选择吗?

    import { async } from '@angular/core/testing';

    describe('MyService', () => {
        let service: MyService;

        ...

        it('should get data', async( async() => {
            // arrange
            let expectedData = { answer: 42 …
Run Code Online (Sandbox Code Playgroud)

unit-testing karma-jasmine angular angular-test angular7

6
推荐指数
1
解决办法
3135
查看次数

rxjs 如何期望 observable 抛出错误

在我的 TypeScript 应用程序中,我有一个返回 rxjs Observable 的方法,在某些情况下,它可以返回throwError

import { throwError } from 'rxjs';

// ...

getSomeData(inputValue): Observable<string> {
  if (!inputValue) {
    return throwError('Missing inputValue!');
  }

  // ...
}
Run Code Online (Sandbox Code Playgroud)

我如何编写测试来涵盖这个特定情况?

jasmine rxjs typescript angular angular-test

6
推荐指数
2
解决办法
3224
查看次数

ng 测试在角度通用错误“不完整:未找到规格,随机种子 48751”中失败

在运行“ng test”命令时将 angular 7 项目转换为 angular Universal,错误为“ Incomplete: No specs found, , randomized with seed 48751”。尝试了不同的方式提及 stackoverflow,但对我来说没有任何作用。

ERROR in ./src/polyfills.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: ../src/polyfills.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
    at AngularCompilerPlugin.getCompiledFile (../node_modules/@ngtools/webpack/src/packages/ngtools/webpack/src/angular_compiler_plugin.ts:1024:15)
    at plugin.done.then (../node_modules/@ngtools/webpack/src/packages/ngtools/webpack/src/loader.ts:49:29)
    at process._tickCallback (internal/process/next_tick.js:68:7)
 @ multi ./src/polyfills.ts ./node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/jit-polyfills.js polyfills[0]
Run Code Online (Sandbox Code Playgroud)

预期输出为 ng test 命令正常运行而不会出现任何问题,以便我的单元测试用例执行。

angular-universal angular angular-unit-test angular-test

6
推荐指数
2
解决办法
9146
查看次数

Angular ngrx 存储测试`状态中不存在功能名称“storeOne”

在我浏览了下面的 ngrx 隔离测试视频后: John Crowson - 在 NgRx 8 中使用 MockStore | 角度向上

我尝试在我的简单项目中实现相同的功能。但是我收到了我无法理解的错误。有人帮我解决吗?

这对我帮助很大。

测试 ts 文件:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { provideMockStore, MockStore } from '@ngrx/store/testing';
import { ShellHomeComponent } from './shell-home.component';
import { StoreOne } from './../../models';
import { Store, select } from '@ngrx/store';
import { cold } from 'jasmine-marbles';

describe('ShellHomeComponent', () => {

    let component: ShellHomeComponent;
    let fixture: ComponentFixture<ShellHomeComponent>;
    let mockStore: MockStore<StoreOne>;

    const loadingState = {
        loading: true,
        items: [{ name: …
Run Code Online (Sandbox Code Playgroud)

ngrx-store angular-test angular8 ngrx-store-8.0

6
推荐指数
1
解决办法
2993
查看次数

即使所有表单字段都有效,Angular 表单也无效

我正在尝试解决一个Angular 表单验证 动手,为此我制作了以下表单,该表单通过了除一个之外的所有测试用例,看起来问题出在测试文件(app.component.spec.ts)上动手操作的只读 工作演示将表单状态显示为VALID。但它没有通过测试

过去两天我一直坚持使用这种手工表格。衷心感谢您的帮助

-----------[只读]app.component.spec.ts---------

import { AppComponent } from './app.component';
import { ReactiveFormsModule, FormControl, AbstractControl, FormGroup } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { asNativeElements, DebugElement } from '@angular/core';

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule],
      declarations: [AppComponent]
    })
    .compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
  }));

  // it('should create the component', () => {
  //   expect(component).toBeTruthy();
  // …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms angular-test

6
推荐指数
1
解决办法
5081
查看次数

使用 asyncScheduler 和 flush 进行角度测试 - 为什么它会因 flush() 而失败?

有这个 Angular 组件:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { asyncScheduler, Observable, of, queueScheduler, scheduled } from 'rxjs';

@Component({
  selector: 'test-component',
  templateUrl: './test-component.component.html'
})
export class TestComponentComponent implements OnInit {
  value: string;

  constructor() { }

  ngOnInit(): void {
    const data$ = this.fetchDataScheduler();

    data$
      .subscribe(value => {
        this.value = value;
      });
  }

  private fetchDataScheduler(): Observable<string> {
    return scheduled(of('foo'), asyncScheduler);
  }

}

Run Code Online (Sandbox Code Playgroud)

并且测试失败:

it('async - test setTimeout', fakeAsync(() => {
    expect(component.value).toBeFalsy();

    fixture.detectChanges(); // ngOnInit

    expect(component.value).toBeFalsy();
    flush();

    expect(component.value).toBe('foo');  // <- …
Run Code Online (Sandbox Code Playgroud)

rxjs angular angular-test

6
推荐指数
1
解决办法
608
查看次数