标签: angular-test

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

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

karma-jasmine angular angular-test

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

如何在获取代码覆盖率时排除规范文件 [Angular]

我正在尝试获取我的角度项目的代码覆盖率。我不太熟悉这些工具。我决定使用"istanbul-instrumenter-loader": "^3.0.1". 我尝试从这个问题中寻求帮助:

  1. 角度cli排除文件/目录ng test--code-coverage
  2. 与spec.ts和spec.tsx不匹配但应匹配任何其他.ts和.tsx的正则表达式

以及在同一线程上给出的许多其他解决方案。我的问题是我想排除我为单元测试编写的规范文件。这是我得到的屏幕截图: 截图。请纠正我的错误,并随时询问缺失的信息。

code-coverage istanbul karma-jasmine angular angular-test

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

Typescript 与“typeof”相反/反向操作

Angular 可以按类型查询子组件,在测试中使用它,如下所示:

fixture.debugElement.query( By.directive( ComponentType ) );
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个为我执行此操作的函数:

import { ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Type } from '@angular/core';

export function findSubComponent<T>( fixture: ComponentFixture<any>, componentType: T & Type<any> ): T {
  const subComponentDebugElement = fixture.debugElement.query( By.directive( componentType ) );
  return subComponentDebugElement.componentInstance;
}
Run Code Online (Sandbox Code Playgroud)

现在问题来了。我的函数当前返回typeof ComponentType而不是实际的对象ComponentType,因此我无法访问它的属性。

这里的 TypesubComponentDebugElement.componentInstance是 any,所以我可以在返回 Type 参数中声明类型(function (): T

typeof ComponentInstance我怎样才能将本例中代表的 T 变成ComponentInstance

typescript typescript-generics angular2-testing angular angular-test

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

为什么我的单元测试通过Chrome并且使用PhantomJS失败?

我正在使用Angular2 final(2.0.2)和angular-cli.我正在尝试将其设置为使用PhantomJS运行单元测试.使用Chrome和karma-chrome-launcher运行规范 - 所有测试都通过.运行相同的Phantomjs-prebuilt 2.1.13和karma-phantomjs-launcher 1.0.2测试失败.

我将phantomjs启动器添加到karma.conf中的plugins数组,以及浏览器数组中的PahntomJS.

我得到的错误是:

PhantomJS 2.1.1(Mac OS X 0.0.0)DataTableFormat应以毫秒为单位转换日期FAILED ReferenceError:找不到变量:src/main/js/test.ts中的Intl(第53565行)intlDateFormat @ webpack:/// Users /sninio/dev/csp-ui/~/@angular/common/src/facade/intl.js:117:0 < - src/main/js/test.ts:53565:20 webpack:/// Users/sninio /dev/csp-ui/~/@angular/common/src/facade/intl.js:148:36 < - src/main/js/test.ts:53596:59 dateFormatter @ webpack:/// Users/sninio /dev/csp-ui/~/@angular/common/src/facade/intl.js:157:0 < - SRC /主/ JS/test.ts:53605:39格式@的WebPack:///用户/ sninio /dev/csp-ui/~/@angular/common/src/facade/intl.js:192:0 < - SRC /主/ JS/test.ts:53640:29变换@的WebPack:///用户/ sninio /dev/csp-ui/~/@angular/common/src/pipes/date_pipe.js:92:0 < - SRC /主/ JS/test.ts:70473:90变换@的WebPack:///用户/ sninio /dev/csp-ui/src/main/js/app/pages/+platform/events/data-table/data-table.pipe.ts:9:4418 < - src/main/js/test.ts:52698 :5787 webpack:/// Users/sninio/dev/csp-ui/src/main/js/app/pages/+ platform/events /data-table/data-table.pipe.spec.ts:20:30 < - src/main/js/test.ts:60923:30执行@ webpack:/// Users/sninio/dev/csp-ui/~/@angular/core/bundles/core-testing.umd.j < - src/main/js/test.ts:2997:28 webpack:/// Users/sninio/dev/csp-ui /〜/ @ angular /core/bundles/core-testing.umd.js:951:32 < - src/main/js/test.ts:3084:56调用@ webpack:/// Users/sninio/dev/csp-ui …

phantomjs karma-runner angular-cli angular angular-test

4
推荐指数
1
解决办法
6258
查看次数

如何使用可观察服务测试组件错误处理

语境

我正在尝试测试一个组件。在另一篇文章中,我询问了有关测试直接函数调用的问题。在这里,我使用相同的示例组件专注于我的组件的错误处理。

我想测试,当我的服务返回一个可观察到的错误时,我的组件是否正确调用了 console.error(error)。

如何“创建”此错误触发器并测试我的组件是否正确处理它。我听说间谍可以做到这一点,但我不知道在哪里设置这个间谍。

我想模拟服务上的 http 请求可能失败的情况。出于任何原因或任何错误代码。

代码

这是组件、存根服务和我的规范文件的代码。

成分

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

import { UserManagementService } from '../../shared/services/global.api';
import { UserListItemComponent } from './user-list-item.component';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html'
})
export class UserListComponent implements OnInit {
  public userList = [];

  constructor(
    private _userManagementService: UserManagementService,    
  ) { }

  ngOnInit() {
    this.getUserList();
  }

  onRefreshUserList() {
    this.getUserList();
  }

  getUserList(notifyWhenComplete = false) {
    this._userManagementService.getListUsers().subscribe(
      result => {
        this.userList = result.objects;
      },
      error => {
        console.error(error); // That's …
Run Code Online (Sandbox Code Playgroud)

jasmine typescript karma-jasmine angular angular-test

4
推荐指数
1
解决办法
7581
查看次数

如何在单元测试中模拟 ApplicationRef

我试图通过 Jasmine 和 Angular 4 测试这两种方法,但this.applicationRef总是返回一个空对象。这个怎么解决?

这是我的代码:

@Injectable()
class Dialog {
  ....
  getRootViewContainerRef(): ViewContainerRef {
    const appInstance = this.applicationRef.components[0].instance;

    if (!appInstance.viewContainerRef) {
      const appName = this.applicationRef.componentTypes[0].name;
      throw new Error(`Missing 'viewContainerRef' declaration in ${appName} constructor`);
    }

    return appInstance.viewContainerRef;
  }
}

createOverlay(parentContainerRef: ViewContainerRef): ComponentRef<DialogContainerComponent> {
  const rootContainerRef = parentContainerRef;
  const rootInjector = rootContainerRef.injector;

  const bindings = ReflectiveInjector.resolve([]);
  const injector = ReflectiveInjector.fromResolvedProviders(bindings, rootInjector);

  const overlayFactory = this.cfr.resolveComponentFactory(DialogContainerComponent);
  return rootContainerRef.createComponent(overlayFactory, rootContainerRef.length, injector);
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试脚本:

describe('Dialog service', () => {
  //let fixture: ComponentFixture<DialogInformationComponent>; …
Run Code Online (Sandbox Code Playgroud)

angular angular-test

4
推荐指数
1
解决办法
3098
查看次数

如何重用Angular测试文件中的所有导入

可以说我有一个简单的模块AppModule,其中包含许多导入,声明和提供程序。现在,我想ListComponent为位于此模块的声明列表中的组件编写测试。ListComponent本身使用的很多(但不是每次)导入AppModule。我这样做是这样的:

import { TestBed } from '@angular/core/testing';
// +same copy-pasted list of imports from `AppModule`

beforeEach(done => {
    TestBed.configureTestingModule({
        imports: [
            // +same copy-pasted list of imports from `AppModule`
        ],
        declarations: [
            // +same copy-pasted list of declarations from `AppModule`
        ],
        providers: [
            {
                provide: Http,
                useClass: HttpMock,
            },
            {
                provide: Router,
                useClass: RouterMock,
            }
            // +same copy-pasted list of providers from `AppModule`
        ]
    });
Run Code Online (Sandbox Code Playgroud)

它有效,但是肯定是不正确的方法。我不想复制粘贴太多。也许我可以通过一些方便的方法重用AppModule?伪代码如下:

let appModule = new AppModule();

beforeEach(done …
Run Code Online (Sandbox Code Playgroud)

angular-module angular-components angular angular-test angular-testing

4
推荐指数
1
解决办法
2823
查看次数

使用retry()和HttpClientTestingModule测试HTTP请求

我想测试一个HTTP调用错误响应HttpClientTestingModule.这工作正常,直到我retry(2)向HTTP调用添加rxjs .然后,测试显然抱怨发现了意外的请求:

预计没有公开要求,发现1

但现在,我不知道如何使用以下两个请求HttpTestingController:

service.ts

@Injectable()
export class Service {
  constructor(private http: HttpClient) { }

  get() {
    return this.http.get<any>('URL')
      .pipe(
        retry(2),
        catchError(error => of(null))
      )
  }
}
Run Code Online (Sandbox Code Playgroud)

service.spec.ts

describe('Service', () => {
  let httpTestingController: HttpTestingController;
  let service: Service;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [Service],
      imports: [HttpClientTestingModule]
    });

    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(Service);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  it('should handle 404 with retry', () => {
    service.get().subscribe((data: any) => {
      expect(data).toBe(null);
    });
    expectErrorResponse(404); …
Run Code Online (Sandbox Code Playgroud)

jasmine typescript angular angular-httpclient angular-test

4
推荐指数
1
解决办法
1576
查看次数

全局设置业力茉莉花 DEFAULT_TIMEOUT_INTERVAL

在我的 Angular 应用程序中,我使用 Karma 和 Jasmine 来运行我的单元测试。

我想将异步测试的默认超时间隔从默认的 5 秒更改为 10 秒。

我看到你可以用jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000它来完成它。

但是,我想通过一些配置文件全局更改它。例如在karma.conf.js但我没有看到defaultTimeoutInterval可用的选项。

jasmine karma-runner karma-jasmine angular angular-test

4
推荐指数
1
解决办法
2010
查看次数

Angular11 测试:ReferenceError:未定义 ResizeObserver

ResizeObserver在我的组件中使用过,它工作正常。但是运行ut时出现这样的错误:

    ReferenceError: ResizeObserver is not defined

      133 |             });
      134 |         
    > 135 |         this.resizeObserver = new ResizeObserver((entries) => {
          |                                   ^
      136 |             const entry = entries.find((e) => e.target === this.wrapper._elementRef.nativeElement);
      137 |             if (entry && entry.contentRect) {
      138 |                 if (this.select && this.select.isOpen) {
Run Code Online (Sandbox Code Playgroud)

我使用 TestBed 创建组件:

fixture = TestBed.createComponent(MyComponent);
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会出现这个错误,我只是新建了一个对象。

ts 版本

"rxjs": "~6.5.5",
"tslib": "^2.0.0",
"zone.js": "~0.10.3"
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

testbed angular angular-test angular11

4
推荐指数
1
解决办法
1972
查看次数