标签: angular-test

TestBedStatic 类型上不存在属性“configureTestingModule”

我已使用 Angular 12 应用程序将 Angular 12 应用程序更新为 Angular 14 ng update。构建成功,可以看到我的应用程序运行得很好,但我的测试失败了。我遇到的错误之一是:

TestBedStatic 类型上不存在属性“configureTestingModule”

有人知道这个问题有什么解决方法吗?我需要更新我的测试库吗?

@angular/core: ^14.2.0
jasmine-core: ~3.8.0
jasmine-marbles: ^0.8.3
karma: ~6.3.0
protractor: ^7.0.0
Run Code Online (Sandbox Code Playgroud)

样品测试:

beforeEach( () => {
    TestBed.configureTestingModule({
        providers: []
    });
})
Run Code Online (Sandbox Code Playgroud)

testbed angular angular-test angular12 angular14

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

测试功能性 Angular 路由防护

您好,由于类防护已被弃用,我将其移至功能性,但我的测试失败了,我对 keycloak 的可注入服务和防护的参数感到非常困惑。

这是守卫:

export const authGuard: CanActivateFn = async (
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Promise<boolean> => {
  const keycloak = inject(KeycloakService);
  const isLogged = await keycloak.isLoggedIn();

  if (!isLogged) {
    await keycloak.login({
      redirectUri: window.location.origin + state.url,
    });
    return false;
  }
  return true;
};
Run Code Online (Sandbox Code Playgroud)

这是我的测试:

import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { KeycloakService } from 'keycloak-angular';
import { authGuard } from './auth.guard';

describe('authGuard', () => …
Run Code Online (Sandbox Code Playgroud)

angular-routing angular angular-test angular-guards

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

在angular 4项目中模拟功能性e2e量角器测试中的其余调用

我们有一个庞大的项目,我们编写了许多测试用例,以涵盖e2e功能测试用例中的许多实际场景用户行为。

随着测试的进行,它会进行大量的调用以完成测试用例。当我们在酱料实验室中使用其他浏览器时,它会倍增5-9倍。

我要模拟所有其余的调用,这样就不会对实际服务器进行任何真正的调用,但是会在内部对其进行处理。它用于功能e2e测试,而不是单元测试,因为我们使用jasmine模拟了所有单元测试spyOn

我已经探索json-server$httpBackend量角器。子服务器不合适,因为它不能很好地处理应用程序的发布,放置,删除呼叫。如果是$ httpBackend

我已经看完了这篇文章,它涉及的是andularJs应用程序而不是angular应用程序,也涉及到有关angularJs的单个rest调用模拟,而不是所有rest调用。

为angularjs看了这个angularjs 多重模拟,也为angularjs 看到了它,而不是angularjs,看起来像这样更改了查询参数的原始REST URL。

protractor angular-mock angular angular-e2e angular-test

3
推荐指数
1
解决办法
6425
查看次数

如何测试Material2 Snak-bar?

我有一个关于Angular 5的项目,遇到以下问题。我有一个组件ComponentWithSnackBar,它触发显示小吃店:

showSnackBar() {
  this.snackBar.open('Message text', 'Close', {
    duration: 5000,
    verticalPosition: 'top',
  });
}
Run Code Online (Sandbox Code Playgroud)

它按预期工作。但是我不知道如何测试。我尝试编写测试:

describe('ComponentWithSnackBar', () => {
  let snackBar: MatSnackBar;
  let overlayContainer: OverlayContainer;
  let overlayContainerElement: HTMLElement;

  function createComponent<T>(component: Type<T>, providers: Provider[] = [], declarations: any[] = []): ComponentFixture<T> {
    TestBed.configureTestingModule({
      imports: [AppModule, RouterTestingModule, NoopAnimationsModule],
      declarations: declarations,
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers,
    }).compileComponents();

    inject([MatSnackBar, OverlayContainer], (sb: MatSnackBar, oc: OverlayContainer) => {
      snackBar = sb;
      overlayContainer = oc;
      overlayContainerElement = oc.getContainerElement();
    })();

    return TestBed.createComponent<T>(component);
  }

  it(`Should display snack-bar`, fakeAsync(() => {
    const …
Run Code Online (Sandbox Code Playgroud)

karma-jasmine angular-material2 angular angular-test

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

如何在 Angular 2 中为单元测试创​​建新事件?

嗨,我正在为我的 angular 代码编写单元测试用例。我正在尝试更新 gridview 中的文本框。下面是我的 gridview 代码。

<input *ngIf="editing[rowIndex + '-scopevalue']" class="inline-editor" autofocus (blur)="updateValue($event, 'scopevalue', value, rowIndex)" type="text" [value]="value" />
Run Code Online (Sandbox Code Playgroud)

下面的函数执行更新。

 updateValue(event, cell, cellValue, rowIndex) {
        this.editing[rowIndex + '-' + cell] = false;
        this.rows[rowIndex][cell] = event.target.value;
        this.rowsCache[rowIndex][cell] = event.target.value;
        this.scopeEdit = this.rows[rowIndex];
        this.updateScope();
    }
Run Code Online (Sandbox Code Playgroud)

在单元测试用例下面,我正在编写检查上面的代码。

 it('update scope name value', () => {
        var row = component.rows[0];
        let cell = 'scopevalue';
        let cellValue = row.scopevalue;
        let rowIndex = 0;
        component.updateValue('/bmw', cell, cellValue, rowIndex);
    });
Run Code Online (Sandbox Code Playgroud)

在上面的方法中,第一个参数应该是事件。有人可以帮助我如何创建活动吗?任何帮助,将不胜感激。谢谢

typescript karma-jasmine angular angular-test

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

角度测试 - 可观察管道不是函数

我想为照片上传方法编写单元测试。但我得到了Failed: this.task.snapshotChanges(...).pipe is not a function TypeError: this.task.snapshotChanges(...).pipe is not a function错误。

为了这个问题的简单起见,我将代码全部放在一种方法中:

成分

  public startUpload(event: FileList) {
    const file: File = event.item(0);
    const pathRef = `users/${this.uid}`;

    this.task = this.service.uploadPhoto(pathRef, file);
    this.fileRef = this.service.getFileReference(pathRef);
    this.percentage = this.task.percentageChanges();
    this.snapshot = this.task.snapshotChanges();
    this.task.snapshotChanges().pipe(last(), switchMap(() => // it fails here - need to propperly mock this
    this.fileRef.getDownloadURL()))
      .subscribe(url => this.service.updatePhoto(url));
  }
Run Code Online (Sandbox Code Playgroud)

组件.spec

  it('should upload file', async(() => {
    const supportedFile = new File([''], 'filename.png', {type: 'image/', lastModified: 2233});
    const fileList = …
Run Code Online (Sandbox Code Playgroud)

jasmine rxjs karma-jasmine angular angular-test

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

Angular 组件测试错误:TypeError 无法读取未定义的属性“订阅”

我有一个简单的单元测试,它是在 Angular 6 组件上使用 karma/jasmine 完成的。从我收集的复数课程和文档来看,我似乎正在正确地模拟我的组件所需的服务,但是当调用该方法从模拟服务返回数据时,我收到错误消息,指出属性订阅未定义。

我的“it”函数是空的,因为一旦在 beforeEach 方法中构造了组件,测试就会失败。组件的构造函数调用了我试图测试的方法。请在下面查看我的代码。

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { MainComponent } from './main.component';
import { DataService } from '../services/data.service';
import { of } from 'rxjs';
import { NO_ERRORS_SCHEMA } from "@angular/core";

describe('Should construct MainComponent', () => {
	let mainComponent: MainComponent;
	let EMPLOYEES;
	let fixture: ComponentFixture<MainComponent>;
	let mockDataService;

	beforeEach(() => {
		EMPLOYEES = [
			{
				"PrismEmployeeID": 1,
				"FirstName": "install2",
				"LastName": "account",
				"Initials": "IA ",
				"NickName": "",
				"SSN": "",
				"DateOfBirth": "09/26/2014",
				"HireDate": …
Run Code Online (Sandbox Code Playgroud)

unit-testing jasmine angular angular-test

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

使用角度测试 fakeAsync 和 jest it.each

使用 Angular 8、@angular-builders/jest 8.0.2、jest 24.8,并给出以下测试通过

import { tick, fakeAsync } from '@angular/core/testing';

it('test 1000 milliseconds', fakeAsync(() => {
    const fn = jest.fn();
    setTimeout(() => {
        fn();
    }, 1000);

    tick(999);
    expect(fn).not.toHaveBeenCalled();
    tick(1);
    expect(fn).toHaveBeenCalled();
}));

Run Code Online (Sandbox Code Playgroud)

我想使用编写几个类似的测试it.each

it.each([[1000], [2000], [3000]])(
    'test %d milliseconds',
    fakeAsync(milliseconds => {
        const fn = jest.fn();
        setTimeout(() => {
            fn();
        }, milliseconds);

        tick(milliseconds - 1);
        expect(fn).not.toHaveBeenCalled();
        tick(1);
        expect(fn).toHaveBeenCalled();
    }),
);

Run Code Online (Sandbox Code Playgroud)

但我在每次测试中都遇到这个错误:

Expected to be running in 'ProxyZone', but it was not found.

    at Function.Object.<anonymous>.ProxyZoneSpec.assertPresent (node_modules/zone.js/dist/proxy.js:42:19)
    at node_modules/zone.js/dist/fake-async-test.js:588:47
Run Code Online (Sandbox Code Playgroud)

我缺少什么?

jestjs angular angular-test ts-jest

3
推荐指数
1
解决办法
7528
查看次数

NgRx 8 测试 provideMockStore - 状态切片的 setState

我的 NgRx 实现有一个智能组件测试,如下所示:

describe( 'Component', () => {
  let store: MockStore<State>;

  beforeEach( async( () => {
    TestBed.configureTestingModule( {
        /* ... */
        providers: [
            provideMockStore( { initialState: fromReducer.initialState } )
        ]
    } ).compileComponents();
    store = TestBed.get<Store<State>>( Store );
  } ) );

  it( 'should load items in #ngOnInit', () => {
    store.setState( {
        item: {
          ...fromReducer.initialState,
          entities: { [item.id]: item },
        },
        otherFeature: null,
        otherFeature: null,
        otherFeature: null
    } );
    component.items$.subscribe( items =>
        store.select( ItemStoreSelectors.selectItems ).subscribe( fromStore => expect( items ).toEqual( fromStore …
Run Code Online (Sandbox Code Playgroud)

typescript ngrx angular ngrx-store angular-test

3
推荐指数
1
解决办法
6190
查看次数

如何在角单元测试中模拟ControlContainer?

如何模拟一个ControlContainer实例,以便测试我的组件?

我有一个将a ControlContainer注入构造函数的子组件,因此其用法是

<acr-score-card formGroupName="score"></acr-score-card>
Run Code Online (Sandbox Code Playgroud)

组件本身是

@Component({
  selector: 'acr-score-card',
  templateUrl: './score-card.component.html',
  styleUrls: ['./score-card.component.scss']
})
export class ScoreCardComponent implements OnInit {

  ...

  form: FormGroup;

  constructor(private ngControl: ControlContainer) { }

  ngOnInit() {
    this.form = <FormGroup>this.ngControl.control;
  }

  ...

}
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中运行时,一切正常,但由于不确定如何模拟ControlContainer实例以设置提供程序,因此无法使单元测试正常工作,这是我的spec文件的内容:

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [TestingModule],
      declarations: [ScoreCardComponent],
      providers: [/** what goes here to mock the ControlContainer */]
      schemas: [NO_ERRORS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = …
Run Code Online (Sandbox Code Playgroud)

angular angular-test

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