I am trying to send the POST request to my '/convert' route but I am getting body as an empty object in that route. I am using Supertest and mock-fs(to mock my file system). If I remove the mock({...}) method from my test file and try to send the same POST request then it is working perfectly fine. I am getting the req.body value in the '/convert' route while not using mock({...}) method. I want the mock-fs to work while sending the POST request using Supertest and the body should be available in the '/convert' route.
Please help or suggest me what I am doing wrong as I have already searched a lot but couldn't get any useful information on this scenario.
// testing.spec.ts
import request from 'supertest';
import mock from 'mock-fs';
describe('Converts HTML to PDF', () => {
beforeEach(() => {
const mockStorage = {
mode: 0o777,
items: {
'654321': mock.directory({mode: 0o775})
}
}
const mockAppDirectory = {
mode: 0o777,
items: {
'storage': mock.directory(mockStorage)
}
}
mock({
'/app': mock.directory(mockAppDirectory)
})
});
afterEach(function() {
mock.restore();
});
test('test', async (done) => {
const testData = {
header:"test",
footer:"test",
body:"test",
dpi:200,
filename:"test",
};
const res = await request(app)
.post('/convert')
.send(testData)
.expect(200)
done();
});
})
// testRoute.ts
import express from "express";
const router = express.Router();
router.post('/convert', async (req: Request, res: Response) => {
console.log(JSON.stringify(req.body));
);
export default router;
Here is the solution after spending days. In order to fetch the body from the request we need body-parser and body-parser is present in the node_modules directory. By default, all files are lazy loaded in mock-fs so mock-fs only mocks and loads those directories which we specify using the mock function. In my code, I am not explicitly loading the node_modules directory and hence mock-fs is not aware of the body-parser module. So, I tried loading the node_modules explicitly and worked like a charm.
mock({
// @ts-ignore
'node_modules': mock.load(path.resolve('node_modules')),
'/app': mock.directory({ mode: 0o775 })
});