Javascript 使用Jest和Supertest进行测试时服务器导出出现问题
我正在使用Jest和Supertest测试一个带有Express后端的React应用程序。在我当前的测试中,我需要存根获取,这是我用Supertest做的。问题是,我从未从代理get()获得答案,因此从未获得任何数据 我认为我如何导出服务器存在问题。我尝试过改变导出,从module.exports=app到module.exports={app},再到const server=app.listen(端口等),以及module.exports=server。到目前为止,我发现的解决方案都不起作用 server.js:Javascript 使用Jest和Supertest进行测试时服务器导出出现问题,javascript,reactjs,jestjs,supertest,Javascript,Reactjs,Jestjs,Supertest,我正在使用Jest和Supertest测试一个带有Express后端的React应用程序。在我当前的测试中,我需要存根获取,这是我用Supertest做的。问题是,我从未从代理get()获得答案,因此从未获得任何数据 我认为我如何导出服务器存在问题。我尝试过改变导出,从module.exports=app到module.exports={app},再到const server=app.listen(端口等),以及module.exports=server。到目前为止,我发现的解决方案都不起作用
const app = require('./app.js');
const port = process.env.PORT || 8080;
app.listen(port, () => console.log("Server running on port " + port));
app.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;
home-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);
}
});
我希望stubbed fetch将返回一个包含七个json菜单的列表。进一步调试表明它确实可以工作。
response=await agent.get(url)
最终还是可以工作的,但是到那时测试已经失败了。结果表明测试中的谓词是错误的,它在寻找一个总是在那里的元素,所以它没有先等待响应。进一步的调试表明它确实可以工作。response=await agent.get(url)
最终还是可以工作的,但是到那时测试已经失败了。结果表明测试中的谓词是错误的,它在寻找一个始终存在的元素,所以它没有先等待响应。
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);
});
};
}