标签: angular-test

Angular CLI - 如何在src文件夹之外获取.spec.ts文件?

我有一个NgModule位于/src文件夹外部的Angular CLI项目(最终这个NgModule将打包为npm模块,但现在我只是把它留在了外面/src).

我正在尝试为这个NgModule编写单元测试,但ng test似乎没有拾取.spec.ts文件/src夹之外的文件.

我试过改变路径/src/test.ts:

// Original
const context = require.context('./', true, /\.spec\.ts$/);

// Does not work
const context = require.context('../', true, /\.spec\.ts$/);

// Does not work
const context = require.context('/absolute/path/to/ngmodule', true, /\.spec\.ts$/);
Run Code Online (Sandbox Code Playgroud)

但是我收到一个错误: Module build failed: Error: /absolute/path/to/file.spec.ts is not part of the compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.

我也尝试在以下include属性中添加我的NgModule路径tsconfig.spec.json:

"include": [ …
Run Code Online (Sandbox Code Playgroud)

angular angular-test

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

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
查看次数

带有 Google 登录弹出窗口的 Angular Cypress.io 测试

是否可以使用 Google 身份验证弹出窗口通过 Cypress.io 登录 Google 帐户?

我可以打开窗口,但是赛普拉斯无法检测到电子邮件输入字段的 ID。

错误是:“CypressError:重试超时:预期找到元素:'#identifierId',但从未找到它。”

it('Login', function() {
    cy.visit('home')
    cy.get('#signin-button').click()
    cy.get('#google-login-button').click()
    // cy.wait(1500) // wait doesn't help
    cy.get('#identifierId')
    .type('user@gmail.com') // <<-- error here
  })
Run Code Online (Sandbox Code Playgroud)

angular angular-test cypress

5
推荐指数
1
解决办法
6604
查看次数

Angular 测试中没有 $injector 的提供者

我一直在尝试在我们的混合 AngularJS/NG6 应用程序中设置测试,但哇,这很难做到。我不断收到错误。最新情况如下:

错误:StaticInjectorError(DynamicTestModule)[$injector]:

静态注入器错误(平台:核心)[$injector]:

NullInjectorError: $injector 没有提供者!

我有以下几点component

import { Component, OnInit, Input, Inject } from '@angular/core';
import { DashboardService } from '../../services/dashboard/dashboard.service';

@Component({
    templateUrl: './views/components/dashboard/dashboard.component.html'
})
export class DashboardComponent implements OnInit {
    @Input()
    Session;
    Util;
    constructor(
        private _dashboardService: DashboardService,
        @Inject('Session') Session: any,
        @Inject('Util') Util: any
    ) {
        this.Session = Session;
        this.Util = Util;
    }

    ngOnInit() {
        this._dashboardService
            .getPrograms(this.Session.user.organization)
            .subscribe(
                data => {
                    console.log(data);
                },
                error => {
                    console.log(error);
                }
            );
    }
}
Run Code Online (Sandbox Code Playgroud)

这工作得很好。我可以从我们的 API 中提取数据。另一方面,我有这个spec …

karma-jasmine angular angular-test angular-hybrid

5
推荐指数
1
解决办法
2351
查看次数

没有项目支持 Angular 中的“测试”目标

我想使用“ng test”命令测试 Angular 项目,但收到错误“没有项目支持测试目标”。有谁知道我应该在项目依赖项中添加什么才能使用上述命令运行测试?我不想创建另一个项目只是为了安装这些依赖项并从现有项目复制代码。我应该安装哪些库?npm install karma 和 jasmine 还不够,也许我应该在配置文件中添加一些东西,但我不知道应该添加什么。任何帮助,将不胜感激。

karma-jasmine angular angular-test

5
推荐指数
1
解决办法
9145
查看次数