![](/img/trans.png)
[英]Testing async fs.readfile with Jest and mock-fs has the tests timing out, even with 30 second time out
[英]Not able to post data while using Supertest with mock-fs and Jest
我正在嘗試將POST請求發送到我的'/convert'路由,但我在該路由中將 body 作為一個空對象。 我正在使用Supertest和mock-fs (模擬我的文件系統)。 如果我從我的測試文件中刪除 mock({...}) 方法並嘗試發送相同的POST請求,那么它工作得很好。 我在 '/convert' 路由中獲取req.body值,而不使用 mock({...}) 方法。 我希望 mock-fs 在使用 Supertest 發送 POST 請求時工作,並且正文應該在“/convert”路由中可用。
請幫助或建議我做錯了什么,因為我已經搜索了很多但無法獲得有關這種情況的任何有用信息。
// 測試.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;
這是花了幾天后的解決方案。 為了從請求中獲取正文,我們需要 body-parser 並且 body-parser 存在於 node_modules 目錄中。 默認情況下,所有文件都在 mock-fs 中延遲加載,因此 mock-fs 僅模擬和加載我們使用 mock 函數指定的那些目錄。 在我的代碼中,我沒有顯式加載 node_modules 目錄,因此 mock-fs 不知道 body-parser 模塊。 所以,我嘗試顯式加載 node_modules 並像魅力一樣工作。
mock({
// @ts-ignore
'node_modules': mock.load(path.resolve('node_modules')),
'/app': mock.directory({ mode: 0o775 })
});
不確定您是否應該在 testdata 對象“文件名:測試”中的最后一個值上使用逗號
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.