Closed cfalch closed 6 months ago
Hi @cfalch, seems like something is wrong with your code.
Check what is retuned by res._getData()
.
res._getData()
is an empty string. Do you see anything wrong with the code? This is basically the entire example - it doesn't matter what Validator or Controller do because the jest spys are mocking responses. res.getData()
should be the value of mockControllerResult
-> "{ id: '1', status: 'ok' }". If I add a 2nd await
as I described, _getData()
does then return "{ id: '1', status: 'ok' }"
I think the problem might be that you're trying to test the entire route, but this library is mainly meant for testing the route handler.
Try the following:
const router = new express.Router();
const routeHandler = async (req, res) => {
await Validator.validate(req.body);
const response = await Controller.control(req.body);
res.status(200).json(response);
}
router
.route('/test')
.post(routeHandler);
And in the test change await router(req, res);
to await routeHandler(req, res);
@eugef I appreciate you spending the time to help sort this out. I understand your suggestion which does test out, and will work on refactoring per this example.
With express route:
the following jest test fails with
SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)
At the point I'm parsing JSONData,
res
has statusCode 200, statusMessage 'OK' but _isEndCalled() is false. I've found a very unusual fix, 2 awaits:await await router(req, res);
Am I doing something wrong within the context of the framework, or is this a bug?