[英]Mock express.Router() with Jest
In my code under test, I want to mock router
:在我测试的代码中,我想模拟router
:
import * as express from "express";
const router = express.Router(); // I want to mock this
router.route(...).post(...);
router.route(...).get(...);
In my test:在我的测试中:
import * as express from "express";
test("foo", () => {
jest.mock("express", () => {
Router: () => jest.fn()
});
// ...test stuff
});
But that doesn't work.但这不起作用。 What am I doing wrong?我究竟做错了什么?
Module mock should precede an import.模块模拟应该在导入之前。 In case this happens on top level babel-jest
transform automatically places jest.mock
above import
.如果这种情况发生在顶层babel-jest
转换会自动将jest.mock
放在import
之上。 This cannot happen in case jest.mock
is nested.如果jest.mock
嵌套,则不会发生这种情况。
It should be either:它应该是:
import * as express from "express";
jest.mock("express", () => {
Router: () => jest.fn()
});
...
Or:或者:
test("foo", () => {
jest.mock("express", () => {
Router: () => jest.fn()
});
const express = require('express');
// ...test stuff
});
I used @Estus Flask example and combined it into whole thing.我使用了@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,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.