用Jest模拟express.Router()

时间:2019-02-17 14:16:29

标签: node.js typescript express jestjs

在我的测试代码中,我想模拟application

router

在我的测试中:

import * as express from "express";

const router = express.Router();    // I want to mock this
router.route(...).post(...);
router.route(...).get(...);

但这不起作用。我在做什么错了?

2 个答案:

答案 0 :(得分:2)

模块模拟应该在导入之前。如果这发生在顶级babel-jest上,则转换会自动将jest.mock放在import上方。如果嵌套jest.mock,则不会发生这种情况。

它应该是:

import * as express from "express";

jest.mock("express", () => {
  Router: () => jest.fn()
});

...

或者:

test("foo", () => {
  jest.mock("express", () => {
    Router: () => jest.fn()
  });

  const express = require('express');
  // ...test stuff
});

答案 1 :(得分:2)

我使用@Estus Flask示例,并将其组合成完整的东西。

route/site/index.js

const express = require('express')
const router = express.Router()

const controller = require('../../controller').site

/*
 * Site APIs.
 */

router.get('/', controller.getAll)

module.exports = router

route/site/test/siteRoute.test.js

const siteRouter = require('../')

jest.mock('../../../controller')
jest.mock('express', () => ({
  Router: () => ({
    get: jest.fn(),
  }),
}))

describe('[Router] Site Test', () => {
  test('Exports get with getAll', () => {
    const controller = require('../../../controller').site
    expect(siteRouter.get).toHaveBeenCalledWith('/', controller.getAll)
  })
})

controller/__mocks__/index.js

const site = {
  getAll: jest.fn(),
}

module.exports = {
  site,
}