【问题标题】:e2e testing angular 7: Failed: Cannot read property 'fetchData' of undefinede2e 测试角度 7:失败:无法读取未定义的属性“fetchData”
【发布时间】:2018-11-16 10:12:30
【问题描述】:

我正在尝试在 Angular 7 中对我的服务进行一些 e2e 测试,该方法返回 Observable,这是我的方法:

import { Injectable } from '@angular/core';
import { UrlDecoratorService } from "../../common/url-decorator.service";
import { APIFetcherService } from "../common/api-fetcher.service";
import { Observable } from 'rxjs';
import { IALChrono, ALChrono } from '../../common/IALChrono.interface';

@Injectable()
export class AnnonceChronoDetailService {
    private months: string[];
    constructor(private urlDecoratorService: UrlDecoratorService, private apiFetcher: APIFetcherService) {
    }

    fetchData(chronoInfo: ALChrono): Observable<any> {
        // construct API parameters and URL
        var URL: string = this.urlDecoratorService.urlAPIDecorate("AL", "GetAccessChrono");

        var params = this.urlDecoratorService.generateParameters({
            year: chronoInfo.year,
            month: chronoInfo.month,
            sortBy: chronoInfo.sortBy,
            sortDirection: chronoInfo.sortDirection,
            pageNumber: chronoInfo.currentPage,
            pageSize: chronoInfo.pageSize
        });

        return this.apiFetcher.fetchJson(URL, params);
    }
}

这是我的测试:

import { AppPage } from './app.po';
import { AnnonceChronoDetailService } from '../../src/app/services/annonce-legale/annonce-chrono-detail.service';
import { ALChrono } from '../../src/app/common/IALChrono.interface';
import { APIResponse } from '../../src/app/common/api-response.interface';
import { Observable } from 'rxjs';

describe('workspace-project App', () => {
  let page: AppPage;
  let service: AnnonceChronoDetailService;
  this.chronoInfo = new ALChrono(); //it's a class

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to MyProject!');
  });


  it('#getObservableValue should return value from observable', (done: DoneFn) => {
    service.fetchData(this.chronoInfo).subscribe((resp: APIResponse) => {
      expect(resp.dataCount).toBe(5);
      done();
    });
  });
});

这是我的终端错误:

DevTools listening on ws://127.0.0.1:53112/devtools/browser/2a1d94b2-ef47-4910-9ee2-e875b615ed45
Jasmine started

  workspace-project App
    √ should display welcome message
    × #getObservableValue should return value from observable
      - Failed: Cannot read property 'fetchData' of undefined
          at UserContext.<anonymous> (D:\Front\e2e\src\app.e2e-spec.ts:34:13)
          at new ManagedPromise (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:1077:7)
          at ControlFlow.promise (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2505:12)
          at TaskQueue.execute_ (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:3084:14)
          at TaskQueue.executeNext_ (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:3067:27)
          at asyncRun (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2974:25)
          at D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:668:7
          at <anonymous>
      From: Task: Run it("#getObservableValue should return value from observable") in control flow
          at ControlFlow.emit (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\events.js:62:21)
          at ControlFlow.shutdown_ (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2674:10)
          at shutdownTask_.MicroTask (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2599:53)
      From asynchronous test:
      Error
          at Suite.<anonymous> (D:\Front\e2e\src\app.e2e-spec.ts:33:3)
          at Object.<anonymous> (D:\Front\e2e\src\app.e2e-spec.ts:7:1)
          at Module._compile (module.js:635:30)
          at Module.m._compile (D:\Front\node_modules\ts-node\src\index.ts:439:23)
          at Module._extensions..js (module.js:646:10)
          at Object.require.extensions.(anonymous function) [as .ts] (D:\Front\node_modules\ts-node\src\index.ts:442:12)

**************************************************
*                    Failures                    *
**************************************************

1) workspace-project App #getObservableValue should return value from observable
  - Failed: Cannot read property 'fetchData' of undefined

Executed 2 of 2 specs (1 FAILED) in 6 secs.
[10:02:20] I/launcher - 0 instance(s) of WebDriver still running
[10:02:20] I/launcher - chrome #01 failed 1 test(s)
[10:02:20] I/launcher - overall: 1 failed spec(s)
[10:02:20] E/launcher - Process exited with error code 1
An unexpected error occurred: undefined

我想测试我的返回方法的真正价值,不像单元测试,他们不知道我的方法fetchData

如果您需要更多信息,请告诉我????。

非常感谢。

【问题讨论】:

    标签: angular protractor e2e-testing angular2-observables angular-e2e


    【解决方案1】:

    您还没有创建AnnonceChronoDetailService 的实例(只是创建了引用),这就是service 变量未定义的原因

    let page: AppPage;
    let service: AnnonceChronoDetailService;
    this.chronoInfo = new ALChrono(); //it's a class
    
    beforeEach(() => {
        page = new AppPage();
        service = new AnnonceChronoDetailService(); // create service instance
    });
    

    【讨论】:

    • 是的,我尝试这样做,但是类 AnnonceChronoDetailService 需要像 UrlDecoratorServiceAPIFetcherService 这样的参数,我不知道不知道怎么过。
    • 如果你只是简单地模拟方法,那么你总是可以像service = new AnnonceChronoDetailService(null, null);一样将null传递给它
    • 我这样做了,但我遇到了这个问题失败:无法读取 null 的属性 'urlAPIDecorate' 我做了service = new AnnonceChronoDetailService(new UrlDecoratorService(),null);,我遇到了这个问题- 失败:无法读取 null 的属性 'fetchJson',我这样做了service = new AnnonceChronoDetailService(new UrlDecoratorService(),new APIFetcherService(new Http(new ConnectionBackend(),new RequestOptions())));,我遇到了这个问题 - 失败:未定义 sessionStorage
    • 我已经说过,只有在模拟该方法时,它才有效。我不确定如何在 e2e 测试中注入服务,类似于单元测试中的TestBed.get()
    猜你喜欢
    • 2019-04-28
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多