【问题标题】:How to mock the value of a property in Node/Express using Jest如何使用 Jest 在 Node/Express 中模拟属性的值
【发布时间】:2022-11-12 08:50:42
【问题描述】:

我是开玩笑的新手。我有一个函数可以验证属性的长度。如果超出长度,则函数返回带有400 状态代码的响应。

配置.js

module.exports = {
    maxLength: 50
}

控制器.js

const {
    maxLength
} = require("../config")

const sendMessage = (req, res) => {
        const {
            message
        } = req.body
        if (message.length > maxLength) {
            {
                res.status(400).send()
            }
}

我想在编写单元时将maxLength 的值模拟为2。这样我就可以在不传递太多消息的情况下进行检查。

我尝试了以下方法。

Controller.test.js

const config = require("../config")

confif.maxLimit=jest.fn()

describe('Cntroller.sendMessage', () => {
            it("should return 400 if the message length exceed", async () => {
                config.maxLength = 2;
                req.body = {
                    message: "hello I am new message"
                }
                await sendMessage(req, res)
                expect(res.statusCode).toBe(400)
            )
)

这里我尝试将maxLength的值模拟为2,消息长度为23。所以响应状态码为400。但是测试失败了。

Expected(400)

Recieved(200)

如何模拟maxLength 的值?

提前致谢!

【问题讨论】:

    标签: node.js unit-testing jestjs


    【解决方案1】:

    这会将 maxLength 模拟为不同的值:

    jest.mock("../config", () => ({
      maxLength: 2
    }))
    

    由于 maxLength 不是函数,我不确定如何更改模拟值以针对不同的测试具有不同的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-11
      • 2019-05-12
      • 2020-06-08
      • 2021-11-30
      • 1970-01-01
      • 2019-09-26
      • 2021-05-01
      • 1970-01-01
      相关资源
      最近更新 更多