开玩笑:无法使用构造函数中的参数测试特定类

时间:2018-07-20 13:44:03

标签: angular typescript jestjs

我使用Jest作为单元测试框架。我想测试一个名为EDVApi(edv.ts)的类:

import { Http } from '@angular/http';
import { File } from '@ionic-native/file';
import { FilePath } from '@ionic-native/file-path';
import {Headers} from '@angular/http';
import {RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import {Response} from '@angular/http/src/static_response';
import { Inject } from '@angular/core';

export default class EDVApi {
webservice: any = "https://XXX.XXX.XXX.XXX:YYYYY/";

public constructor(public http: Http) {
console.log('EDVApi created.');
}

login(loginData) {
let headers = new Headers();
let data = {
  loginData: loginData
};
headers.append('Content-Type', 'application/json');

let options = new RequestOptions({
  headers: headers,
  body: JSON.stringify(data)
});

return this.http.post(this.webservice + "login", data, options);
}
public sum(a,b){
return a+b;
}
}

在测试类中,我要测试EDVApi的函数总和:

import EDVApi from './edv';
import 'jest';
jest.mock('./edv');

describe('EDV Tests', () => {
it('Sum 1+2 should be 3', () => {
const mockEDV = EDVApi.mock.instances[0];
expect(mockEDV.sum(1,2)).toBe(3);
});
});

当我尝试编译代码时,cli给我以下错误:属性'mock'在类型'typeof EDVApi'上不存在。当我运行npm test时,玩笑测试失败,并显示以下消息:

   the module which has no default export › Sum 1+2 should be 3

   TypeError: Cannot read property 'mock' of undefined

   5 | describe('the module which has no default export', () => {
   6 |   it('Sum 1+2 should be 3', () => {
>  7 |     const mockEDV = EDVApi.mock.instances[0];
   8 |     expect(mockEDV.sum(1,2)).toBe(3);
   9 |   });
  10 | });

  at Object.<anonymous> (src/edv.test.ts:7:28)

FAIL src \ edv.test.ts   ●测试套件无法运行

TypeError: Cannot read property 'Symbol' of undefined

> 1 |
  2 | import { Http } from '@angular/http';
  3 | import { File } from '@ionic-native/file';
  4 |

  at Object.<anonymous> (node_modules/rxjs/symbol/rxSubscriber.js:3:26)
  at Object.<anonymous> (node_modules/rxjs/Subscriber.js:10:22)
  at Object.<anonymous> (node_modules/rxjs/util/toSubscriber.js:2:20)
  at Object.<anonymous> (node_modules/rxjs/Observable.js:3:22)
  at Object.<anonymous>.Object.setPrototypeOf.__proto__ (node_modules/@angular/core/bundles/core.umd.js:7:82)
  at Object.<anonymous> (node_modules/@angular/core/bundles/core.umd.js:10:2)
  at Object.<anonymous>.Object.setPrototypeOf.__proto__ (node_modules/@angular/http/bundles/http.umd.js:7:82)
  at Object.<anonymous> (node_modules/@angular/http/bundles/http.umd.js:10:2)
  at Object.<anonymous> (src/edv.ts:1:52054)
  at Object.<anonymous> (src/edv.test.ts:3:31)

我尝试了正式的Jest文档中所述的许多不同解决方案,但无法解决此问题。有什么建议吗?

0 个答案:

没有答案