如何在Jest中打桩/模拟方法/构造函数的参数以进行Node.js中的单元测试?

时间:2019-04-23 07:06:36

标签: node.js unit-testing junit jestjs inversifyjs

我对Node js和jsest还是很陌生。我有一个要使用笑话进行单元测试的班级:

import { Observable, from } from 'rxjs';
import { inject, injectable } from 'inversify';
import "reflect-metadata";
import ILogger from './ilogger';
import { ServiceInterface, DaoInterface } from '../interfaces';

@injectable()
class ServiceImpl implements ServiceInterface {
  public loggerService: ILogger;
  private dao: DaoInterface;
  public constructor(@inject("LOGGER") loggerService: ILogger, @inject("DAO") dao: DaoInterface) {
    this.loggerService = loggerService;
    this.dao = dao;
  }
  public get = (id: any): Observable<any> => {
    return from(this.dao.executeQuery(id));
  };
}
export default ServiceImpl;

我在网上搜索了许多教程,但是找不到如何模拟/存根dao(在Java / Junit中完成)以返回存根数据。
我在下面尝试,但感到困惑:

import { ServiceImpl } from '../services';
import { Dao } from '../dao';
import { of } from 'rxjs/internal/observable/of';
import { catchError } from 'rxjs/operators';
import "reflect-metadata";

describe('ServiceImpl Tests', () => {
  let serviceImpl: ServiceImpl;
  beforeAll(() => {
    jest.setTimeout(30000);
    serviceImpl = new ServiceImpl(null, **<WHAT TO PASS HERE AS MOCKED DAO OBJECT>**);
  });

  it('temp test case', done => {
    expect(serviceImpl.get(10)).toMatch('');
    console.log("done===================");
    done();
  });
});

调用dao.executeQuery(id)时要代替 传递什么以及如何返回模拟数据?

请帮助。谢谢。

0 个答案:

没有答案