Ionic + Jasmine + Tslint - 属性'和'在类型上不存在

时间:2017-04-07 14:29:33

标签: typescript ionic-framework jasmine tslint

大家。我正在boilerplate上构建一个Ionic应用程序。 现在,我正在构建特定页面的测试,我正在使用jasmine来模拟提供程序并设置方法的预期行为。 这就是 beforeEach()方法看起来像:

    beforeEach(() => {
          mockLoadingController = jasmine.createSpyObj('ModalController', ['create', 'present', 'dismiss']);
          mockLoadingController.create.and.returnValue(mockLoadingController);

          mockModalController =  jasmine.createSpyObj('LoadingController', ['create', 'present',
            'onDidDismiss', 'dismiss']);
          mockModalController.create.and.returnValue(mockModalController);

          mockGeolocation =  jasmine.createSpyObj('Geolocation', ['getCurrentPosition']);

          mockGeolocation.getCurrentPosition.and.callFake(( ) => {
            return {then: ( ) => { }};
          });
          mockEvents = jasmine.createSpyObj('Events', ['publish', 'subscribe']);
          TestBed.configureTestingModule({
            schemas: [CUSTOM_ELEMENTS_SCHEMA],
            providers: [
              { provide: NavController, useValue: mockNavController },
              { provide: LoadingController, useValue: mockLoadingController },
              { provide: ModalController, useValue: mockModalController },
              { provide: Geolocation, useValue: mockGeolocation },
              { provide: Events, useValue: mockEvents },
              LocationPage,
            ],
          },
    ); } );

当我为 getCurrentPosition 方法定义promise响应时,问题就出现了:

    mockGeolocation.getCurrentPosition.and.callFake(( ) => {
            return {then: ( ) => { }};
    });

我在测试时使用tslint,它给了我以下错误

ERROR in [at-loader] ./src/pages/location/location.page.spec.ts:24:40 
    TS2339: Property 'and' does not exist on type '(options?: GeolocationOptions) => Promise<Geoposition>'.

问题是:我如何克服这个问题,所以TSLint不再抱怨这个代码?

2 个答案:

答案 0 :(得分:2)

问题解决了! 我忘了详细说明我声明变量的方式:

describe('Location Page', () => {
  let mockLoadingController: any;
  let mockModalController: any;
  let mockGeolocation: Geolocation;
  let mockEvents: Events;
  beforeEach(() => {
  //rest of the code here

如您所见,我为 mockGeolocation 变量定义了一个类型,我确实将其他类型设置为任何。将所有变量设置为与jasmine完美配合,并且它不会在tslint中生成错误。

所以正确的代码是这样的:

describe('Location Page', () => {
  let mockLoadingController: any;
  let mockModalController: any;
  let mockGeolocation: any;
  let mockEvents: any;
  beforeEach(() => {

答案 1 :(得分:0)

实际上合适的类型是:

  let mockGeolocation: jasmine.SpyObj<Geolocation>;
  let mockEvents: jasmine.SpyObj<Events>;