javascript - 使用 Jest 和 Supertest 测试 React 时出现服务器导出问题
问题描述
我正在使用 Jest 和 Supertest 测试一个带有 Express 后端的 React 应用程序。在我当前的测试中,我需要对提取进行存根,这是我正在使用 Supertest 进行的。问题是,我从来没有从代理 get() 那里得到答案,因此从来没有得到任何数据。
我认为我如何导出服务器存在问题。我尝试更改导出,从 module.exports = app 到 module.exports = {app},再到 const server = app.listen(port, etc) 和 module.exports = server。到目前为止,我发现的解决方案都没有奏效。
server.js:
const app = require('./app.js');
const port = process.env.PORT || 8080;
app.listen(port, () => console.log("Server running on port " + port));
应用程序.js:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const ews = require('express-ws')(app);
const WebSocket = require('ws');
...
app.get("/menus", (req, res) => {
const menus = MenuRepo.getMenus();
res.json(menus)
})
...
module.exports = app;
主页-test.js
test("Test that dishes displays", async () => {
menuRepo.populateMenus();
overrideFetch(app);
const driver = mount(
<MemoryRouter>
<ShowMenus/>
</MemoryRouter>
);
const predicate = () => {
driver.update();
const tableSearch = driver.find('#menuTable');
const tableIsDisplayed = (tableSearch.length >= 1);
return tableIsDisplayed;
};
const displayedTable = await asyncCheckCondition(predicate, 3000, 200);
expect(displayedTable).toBe(true);
const menus = menuRepo.getMenus();
const html = driver.html();
for(let i=0; i<menus.length; i++){
expect(html).toContain(menus[i].dishes.day);
}
});
我用来存根提取的函数:
function overrideFetch(app){
const agent = request.agent(app);
global.fetch = async (url, init) => {
let response;
if(!init || !init.method || init.method.toUpperCase() === "GET"){
try {
response = await agent.get(url);
} catch (e) {
console.log(e)
}
} else if(init.method.toUpperCase() === "POST"){
response = await agent.post(url)
.send(init.body)
.set('Content-Type', init.headers ? init.headers['Content-Type'] : "application/json");
} else if(init.method.toUpperCase() === "PUT"){
response = await agent.put(url)
.send(init.body)
.set('Content-Type', init.headers ? init.headers['Content-Type'] : "application/json");
} else if(init.method.toUpperCase() === "DELETE"){
response = await agent.delete(url);
} else {
throw "Unhandled HTTP method: " + init.method;
}
const payload = response.body;
return new Promise( (resolve, reject) => {
const httpResponse = {
status: response.statusCode,
json: () => {return new Promise(
(res, rej) => {res(payload);}
)}
};
resolve(httpResponse);
});
};
}
我期待存根提取将返回七个 json 菜单的列表。
解决方案
推荐阅读
- java - javafx中带有Task<>的lineChart
- dax - 从日期表中删除重复行
- active-directory - Azure Active Directory 组 - 控制用户访问
- java - 如何解决在android studio中调用虚拟方法和Sqlite给出NullPointerException?
- csv - 使用具有 csv 值的列将 CSV 文件导入 neo4j
- python - 所以我希望我的机器人在 webbots 上到达所需的坐标
- java - 将鼠标移动到屏幕上的对象
- c++ - 在 C++ 中合并列表
- javascript - iOS JavaScript 声音问题
- python - OR-tools VRP - 系统错误:
返回带有错误集的结果