标签: angular-unit-test

Angular CLI为现有组件创建.spec文件

有一个选项.angular-cli.json可以禁用自动创建*.spec文件,例如组件,请参阅json模式.

这是一个非常好的功能,因为个人(这只是我的意见)测试组件可能不是一个在快速增长的项目中真正值得的东西.

但是,有时我希望有一个选项来*.spec为已经存在的组件/服务/管道/ 生成/重新创建相应的文件.

可以使用一些命令行调用吗?

创建了一个功能请求,让我们看看它是怎么回事......

angular-cli angular angular-unit-test

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

Angular 9 TestBed.inject 和提供者覆盖

由于 TestBed.get 在 Angular 9 中已被弃用,因此当使用提供程序覆盖时,以下替代方案是什么

TestBed.configureTestingModule({
  providers: [{ provide: MyClass, useClass: MyStub}]
});

const obj : MyStub = TestBed.get(MyClass);
Run Code Online (Sandbox Code Playgroud)

真的是这样还​​是有更好的方法?

const obj : MyStub = TestBed.inject(MyClass) as unknown as MyStub;
Run Code Online (Sandbox Code Playgroud)

angular angular-unit-test angular-test angular9

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

"在抛出所有\n [object ErrorEvent]后出现错误"--Angular 4 Unit测试

当我正在进行Angular 4 Unit测试时,对于其中一个使用谷歌地图和agm包的页面显示错误

"在抛出所有\n [object ErrorEvent]之后抛出了一个错误

有谁知道可能是什么问题

控制台截图

angular angular-unit-test

7
推荐指数
3
解决办法
3976
查看次数

在 Angular 单元测试中使用 ngValue 时如何获取 select 的值

在我的 Angular 应用程序中,我绑定了<select>一个反应式表单,如下所示:

<form [formGroup]="myForm">
  <select formControlName="myControlName" id="my-select">
    <option [value]="value" *ngFor="let value of mySelectValues">{{ value }}</option>
  </select>
</form>
Run Code Online (Sandbox Code Playgroud)

在这个阶段,mySelectValues是一个字符串数组。

我像这样进行组件 dom 测试:

it('the select should reflect the form value"', () => {

  // I somehow change the form value to 'ABC' here 
  // and I want to check if the select is correctly showing the change

  const select = fixture.nativeElement.querySelector('#my-select');
  expect(select.value).toEqual('ABC');
});
Run Code Online (Sandbox Code Playgroud)

这很好用。然而,在某些时候,在某些选择中,我需要将对象作为值,而不是在某些地方使用纯字符串/数字。

所以我改变了我的 HTML 代码来[ngValue]使用[value]

<option [ngValue]="value" ...
Run Code Online (Sandbox Code Playgroud)

此时,在我的测试中, 的值 …

typescript angular angular-unit-test angular-test angular-testing-library

7
推荐指数
0
解决办法
546
查看次数

角度测试错误 - NullInjectorError:没有TrimInputDirective的提供者

我创建了一个Angular Directive,它使用CSS选择器自动修剪我的应用程序中的输入,它看起来像......

import { Directive, HostListener, forwardRef } from '@angular/core';
import { DefaultValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

export const TRIM_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => TrimInputDirective),
  multi: true
};

/**
 * The trim accessor for writing trimmed value and listening to changes that is
 * used by the {@link NgModel}, {@link FormControlDirective}, and
 * {@link FormControlName} directives.
 */
/* tslint:disable */
@Directive({
  selector: `
    input
    :not([type=checkbox])
    :not([type=radio])
    :not([type=password])
    :not([readonly])
    :not(.ng-trim-ignore)
    [formControlName],

    input
    :not([type=checkbox])
    :not([type=radio])
    :not([type=password])
    :not([readonly])
    :not(.ng-trim-ignore) …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing angular-directive angular angular-unit-test

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

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

角度服务中 catcherror 管道函数的单元测试

我尝试了解如何测试这个功能。从(err)=>{ line,它显示为一个未覆盖的声明。 服务.ts

Deletevote(inp) {
   console.log(inp);
     
   return this.http.post(environment.apiUrl + '/api/reset/abc', inp).pipe(
      catchError((err) => {
         console.log('error caught in service');
         console.error(err);
         return throwError(err);
      })
   );
}
Run Code Online (Sandbox Code Playgroud)

我已经为正流创建了这个测试用例,但错误部分仍然没有被覆盖。请指导我如何创建错误。

服务规范

const Mockcolor = 'green';
const MockGen = 'male';

it('submitnominGreen', () => {
    service.Deletevote(DeleteObj).subscribe((posts) =>{
      expect(posts).toEqual([Mockcolor,MockGen], 'should check mock data');
    });
    const req =  httpTestCtrl.expectOne(environment.apiUrl + '/api/reset/abc');
    expect(req.request.method).toBe('POST');
    expect(req.cancelled).toBeFalsy();
    req.flush([Mockcolor,MockGen])
});
Run Code Online (Sandbox Code Playgroud)

unit-testing karma-jasmine jestjs angular angular-unit-test

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

如何在 Angular 12 单元测试中对 window.location.reload 进行单元测试?

在我的角度项目中,我有一个函数

reloadPage(): void {
  window.location.reload();
}
Run Code Online (Sandbox Code Playgroud)

因此,每当我需要重新加载页面时,我都会调用此函数。

现在我尝试添加此功能的单元测试,但它不起作用。

it("reloadPage: should be validated", () => {
    spyOn(window.location, 'reload').and.callFake(() => {
      //test
    });
    component.reloadPage();
});
Run Code Online (Sandbox Code Playgroud)

它仍然在单元测试中重新加载页面

如何实现该功能的单元测试?任何帮助都将不胜感激。提前致谢

unit-testing angular angular-unit-test angular12

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

测试角度 if else 块并订阅(response =&gt; {} 茉莉花中的块

我在编写组件方法测试用例时遇到问题。

如何在其内部和内部测试 Angular 组件方法if else块。subscribe((res) => { ///block}ToasterService

我在我的 component.ts 文件中调用了 Angular 服务方法。在服务呼叫内subscribe(response=>{}

我已经验证了块中的响应值if else,并根据结果显示烤面包机消息,但我的业力报告说:response=> function not covered并且if else块内未声明未涵盖。

组件.ts

constructor(private userService: UserService,
    private toastr: ToastrService) { }
sortUsers(sortKey: string) {
    this.userService.getSortUserList(sortKey).subscribe((res) => {
      if(res.Success){
        this.userService.users = res.Data as User[];
      }else{
        this.toastr.error(res.Message);
      }
      
    });
  }
Run Code Online (Sandbox Code Playgroud)

组件规格

it('call sortUser when users are sorted', () => {
    const users: User[] = [{
      User_Id: 1,
      First_Name: 'Madhu Ranjan',
      Last_Name: 'Vannia Rajan', …
Run Code Online (Sandbox Code Playgroud)

jasmine typescript karma-jasmine angular angular-unit-test

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

单元测试 - Angular 9 中未定义的 ag-grid API onFilterChanged

我正在 Angular 中编写 Ag-grid 的单元测试用例,其中有 Angular Grid:外部过滤器,它是切换过滤器复选框。我收到“TypeError:无法读取未定义的属性‘onFilterChanged’”

我正在测试这个方法:

toggleCheckboxMethod({ checked }): void {
    isChecked = checked;
    this.gridApi.onFilterChanged(); //when this method initiates it causes for test to fail
  }
Run Code Online (Sandbox Code Playgroud)
 beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes([]),
        HttpClientModule,
        HttpClientTestingModule,
        AgGridModule.withComponents([]),
        MatDialogModule,
        BrowserAnimationsModule
      ],
      declarations: [ TestComponent ],
      providers: []

    })
    .compileComponents();
  }));

beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

  it('should toggle checkbox', () => {
    let isChecked = false;
    spyOn(component, 'toggleCheckboxMethod').and.callThrough();
    component.toggleCheckboxMethod({ checked: true });
    expect(component.toggleCheckboxMethod).toHaveBeenCalled();
    expect(isChecked).toEqual(true); …
Run Code Online (Sandbox Code Playgroud)

karma-jasmine ag-grid angular angular-unit-test

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