I am new to jest. I have a function where I validate the length of a property. If the length is exceeded, then the function returns the response with the 400
status code.
Config.js
module.exports = {
maxLength: 50
}
Controller.js
const {
maxLength
} = require("../config")
const sendMessage = (req, res) => {
const {
message
} = req.body
if (message.length > maxLength) {
{
res.status(400).send()
}
}
I want to mock the value of maxLength
to 2
when I write the unit tase. So that I can check without passing too many messages.
I have tried the following.
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)
)
)
Here I have tried to mock the value of maxLength
to 2
and the message length is 23. So the response status code will be 400. But the test has failed.
Expected(400)
Recieved(200)
How to mock the value of maxLength
?
Thanks in advance!
CodePudding user response:
This will mock the maxLength
to different value:
jest.mock("../config", () => ({
maxLength: 2
}))
As the maxLength
is not a function I am not sure how could you change the mocked value to have different value for different test.