Typescript Jest模拟:xx.default不是构造函数:无法实例化模拟

时间:2020-04-22 20:11:38

标签: typescript jestjs ts-jest

尝试模拟类和构造函数时遇到麻烦。

我有一个要测试的App.ts类:

class App {
  public server: Express;

  constructor() {
    this.server = new Express();
    this.server.init();
  }
}

export default App;

对于测试场景->一旦我实例化了一个App类,它应该: -确保制作了Express类的新实例 -确保调用了init函数

所以我有我的App.test文件:

import App from '../App';

let mockedExp: jest.Mock;
jest.mock('../Express', () => {
  return {
    default: jest.fn().mockImplementation(() => {
      return {
        init: mockedExp,
      };
    }),
  };
});

describe('App', () => {
  beforeEach(() => {
    mockedExp = jest.fn().mockImplementation();
    mockedExp.mockClear();
  });

  it('Should call init from express with initialize', () => {
    new App();
    expect(mockedExp).toBeCalled();
  });
});

运行测试时,我得到以下信息:

   TypeError: Express_1.default is not a constructor

       8 | 
       9 |   constructor() {
    > 10 |     this.server = new Express();
         |                   ^
      11 |     this.server.init();
      12 |   }

Express类:

import express from 'express';
import Boom from 'express-boom';
import morgan from 'morgan';

import Locals from './Locals';
import Middleware from './Middleware';
import Logger from './Logger';

export default class Express {
  public app: express.Application;

  constructor() {
    this.app = express();

    // disable the x-powered-by header
    this.app.disable('x-powered-by');

    this.app.locals = Locals.getConfig();
    // add boom
    this.app.use(Boom());

    this.app.set('logger', Logger);

    // morgan logger
    /* instanbul ignore next */
    if (this.app.locals.env === 'production') this.app.use(morgan('combined'));
    else {
      this.app.use(morgan('dev'));
    }
  }

  public init(): void {
    const mid = new Middleware(this.app);
    mid.addLogRoutes();
  }

  public start(): void {
    const server = this.app.listen(this.app.locals.PORT, (error: Error) => {
      if (error) {
        throw new Error(`Unable to start server ${error}`);
      }
      /* istanbul ignore next */
      console.log(`Server starting on ${server.address().port}`);
    });
  }
}

我正在使用以下打字稿规则:

"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"noUnusedLocals": true /* Report errors on unused locals. */,
"noUnusedParameters": true /* Report errors on unused parameters. */,
"noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
"strictNullChecks": true,
"strictFunctionTypes": true /* Enable strict checking of function types. */,
"strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */,
"noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
"alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */

那我在做什么错了?

1 个答案:

答案 0 :(得分:2)

have to在返回的对象中指定__esModule: true

jest.mock('../Express', () => {
  return {
    __esModule: true,
    default: jest.fn().mockImplementation(() => {
      return {
        init: mockedExp,
      };
    }),
  };
});

或者,如果默认导出是唯一的导出,则可以直接从工厂返回:

jest.mock('../Express', () => function() { // arrow function cannot be invoked with `new`
  return { init: mockedExp };
});

// or, if you want to spy on the constructor

jest.mock('../Express', () => jest.fn().mockImplementation(() => ({
  init: mockedExp
})));