gpt4 book ai didi

node.js - 用 Jest 模拟 express.Router()

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:01 24 4
gpt4 key购买 nike

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

import * as express from "express";

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

在我的测试中:

import * as express from "express";

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

但这行不通。我做错了什么?

最佳答案

我使用了@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,
}

关于node.js - 用 Jest 模拟 express.Router(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com