角路由单元测试失败

发布于 2025-01-25 14:39:41 字数 4463 浏览 3 评论 0原文

背景:

我有一种简单的反应性形式,用户可以进入地址并选择一些产品来运送到其地址和其他一些细节。一旦提交(调用redirectTopayment()),他们将在n秒后重定向。

问题

我一直在尝试编写一个单位测试用例(Jasmine)。但是,当我尝试执行测试案例时,它正在失败并在终端中获取警告,就像我运行ng Test如下:

'Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?'

当我检查茉莉花的Chrome Console时,会抛出以下例外报告。

ChunkLoadError: Loading chunk 13 failed.
(timeout: http://localhost:9876/_karma_webpack_/13.js)
    at Function.requireEnsure [as e] (bootstrap:126:1)
    at webpackAsyncContext (.*\.entry\.js$ include: \.entry\.js$ exclude: \.system\.entry\.js$ namespace object:185:1)
    at loadModule (index-e806d1f6.js:1947:12)
    at initializeComponent (index-e806d1f6.js:1609:1)
    at index-e806d1f6.js:1750:1
    at ZoneDelegate.invoke (zone-evergreen.js:364:1)
    at FakeAsyncTestZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.FakeAsyncTestZoneSpec.onInvoke (zone-testing.js:1652:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (zone-testing.js:289:1)
    at ZoneDelegate.invoke (zone-evergreen.js:363:1)
    at Zone.run (zone-evergreen.js:123:1) undefined
localConsole.<computed> @ context.js:265
----------------------------------------------------------------------------------------------
Unhandled Promise rejection: Cannot read properties of undefined (reading 'isProxied') ; Zone: ProxyZone ; Task: Promise.then ; Value: TypeError: Cannot read properties of undefined (reading 'isProxied')
    at initializeComponent (index-e806d1f6.js:1616:1) TypeError: Cannot read properties of undefined (reading 'isProxied')
    at initializeComponent (http://localhost:9876/_karma_webpack_/node_modules/@ionic/core/dist/esm/index-e806d1f6.js:1616:1)

茉莉报告

ProductComponent > should navigate to payment page
Expected '' to equal '/payment'.
Error: Expected '' to equal '/payment'.
    at <Jasmine>
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/product/product.component.spec.ts:241:17)
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:1749:1)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)

redirectToPayment() {
    this.form.markAsTouched();

    if (this.form.valid) {      
      const { fName, lName, address, product, paymentMode } = this.form.value;
      this._paymentService.payment(fName, lName, address, product, paymentMode)
      .subscribe(
        res => {           
          setTimeout(() => { this._router.navigate(['/','payment']); }, 2000); 
        }, 
        (err) => {          
          console.error(err);          
        }
      );
   }
}
  • 代码
public payment(fName: string, lName: string, address: string, product: Product[], paymentMode: number) {
  return of({fName, lName, address, product, paymentMode});
}

Suite设置(thereach)

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        SelectProductsComponent
      ],
      imports: [
        HttpClientTestingModule,
        ReactiveFormsModule,
        RouterTestingModule.withRoutes([
          { path: '/payment', component: DummyPaymentComponent }
        ]),
      ],
      providers: [
        FormBuilder,
        PaymentService
      ]
    }).compileComponents();

    router = TestBed.get(Router);
    location = TestBed.get(Location);

    fixture = TestBed.createComponent(SelectProductsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    form = component.productsForm;
}));

失败的单元测试案例

fit('should navigate to payment page', fakeAsync(() => {

    form.patchValue(validFormData);
    fixture.detectChanges();

    const paymentService = TestBed.inject(PaymentService);
    const authSpy = spyOn(paymentService , 'payment').and.returnValue(of(mockSuccessRes));

    component.redirectToPayment();
    fixture.detectChanges();
    
    flush();
    expect(location.path()).toEqual('/payment');
}));

我正在Angular版本10上运行我的项目。

如果我错过了任何细节,有人可以帮我吗?还是我需要采用其他方法?

Background:

I have a simple reactive form where the users enters address and chooses a few products to ship to their address and a few other details. Once they submit (invokes redirectToPayment()) they are getting redirected after N seconds.

Issue

I have been trying to write an unit test case (jasmine) for the same. However, when I try to execute the test case it is failing and getting a warning in the terminal as when I run ng test as below:

'Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?'

And following exceptions are thrown when I check the chrome console of the Jasmine reports.

ChunkLoadError: Loading chunk 13 failed.
(timeout: http://localhost:9876/_karma_webpack_/13.js)
    at Function.requireEnsure [as e] (bootstrap:126:1)
    at webpackAsyncContext (.*\.entry\.js$ include: \.entry\.js$ exclude: \.system\.entry\.js$ namespace object:185:1)
    at loadModule (index-e806d1f6.js:1947:12)
    at initializeComponent (index-e806d1f6.js:1609:1)
    at index-e806d1f6.js:1750:1
    at ZoneDelegate.invoke (zone-evergreen.js:364:1)
    at FakeAsyncTestZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.FakeAsyncTestZoneSpec.onInvoke (zone-testing.js:1652:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (zone-testing.js:289:1)
    at ZoneDelegate.invoke (zone-evergreen.js:363:1)
    at Zone.run (zone-evergreen.js:123:1) undefined
localConsole.<computed> @ context.js:265
----------------------------------------------------------------------------------------------
Unhandled Promise rejection: Cannot read properties of undefined (reading 'isProxied') ; Zone: ProxyZone ; Task: Promise.then ; Value: TypeError: Cannot read properties of undefined (reading 'isProxied')
    at initializeComponent (index-e806d1f6.js:1616:1) TypeError: Cannot read properties of undefined (reading 'isProxied')
    at initializeComponent (http://localhost:9876/_karma_webpack_/node_modules/@ionic/core/dist/esm/index-e806d1f6.js:1616:1)

Jasmine Report

ProductComponent > should navigate to payment page
Expected '' to equal '/payment'.
Error: Expected '' to equal '/payment'.
    at <Jasmine>
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/product/product.component.spec.ts:241:17)
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:1749:1)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)

Code snippets

  • Implementation for redirectToPayment()
redirectToPayment() {
    this.form.markAsTouched();

    if (this.form.valid) {      
      const { fName, lName, address, product, paymentMode } = this.form.value;
      this._paymentService.payment(fName, lName, address, product, paymentMode)
      .subscribe(
        res => {           
          setTimeout(() => { this._router.navigate(['/','payment']); }, 2000); 
        }, 
        (err) => {          
          console.error(err);          
        }
      );
   }
}
  • Implementation for payment() method in Payment service
public payment(fName: string, lName: string, address: string, product: Product[], paymentMode: number) {
  return of({fName, lName, address, product, paymentMode});
}

Test Suite Setup (beforeEach)

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        SelectProductsComponent
      ],
      imports: [
        HttpClientTestingModule,
        ReactiveFormsModule,
        RouterTestingModule.withRoutes([
          { path: '/payment', component: DummyPaymentComponent }
        ]),
      ],
      providers: [
        FormBuilder,
        PaymentService
      ]
    }).compileComponents();

    router = TestBed.get(Router);
    location = TestBed.get(Location);

    fixture = TestBed.createComponent(SelectProductsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    form = component.productsForm;
}));

Failing unit test case

fit('should navigate to payment page', fakeAsync(() => {

    form.patchValue(validFormData);
    fixture.detectChanges();

    const paymentService = TestBed.inject(PaymentService);
    const authSpy = spyOn(paymentService , 'payment').and.returnValue(of(mockSuccessRes));

    component.redirectToPayment();
    fixture.detectChanges();
    
    flush();
    expect(location.path()).toEqual('/payment');
}));

I am running my project on Angular version 10.

Could someone help me if I am missing out any detail ? Or I need to adopt a different approach ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文