【发布时间】:2022-09-27 14:30:15
【问题描述】:
我正在尝试构建一个 npm 包,它是一个快速应用程序,您可以在其中传递和应用程序将使用的路由数组。
我遇到的问题是,当我尝试测试 404 路由或传入参数的数组中的其中一个路由时,开玩笑超时/失败。当我测试默认的/health 路由时,测试通过了。
这是回购https://github.com/byverdu/http-server
// app.mjs
import express from \'express\'
import { healthRouter } from \'./routes/health.mjs\'
function expressApp ({ routes } = {}) {
const app = express();
app.use(\'/health\', healthRouter);
for (const { path, handler, method } of routes) {
// Register all the handlers
app[method](path, handler)
}
app.use((req, res) => {
res.status(404).send(`No handler found for ${req.url}`)
})
return app;
}
export { expressApp }
// server.mjs
import { expressApp } from \'./app.mjs\'
function httpServer ({ port, routes } = {}) {
const PORT = port || 3000
const server = expressApp({ routes })
return server.listen(PORT, () => {
console.log(`App running on: ${PORT}`)
})
}
// usage
const routes = [
{
method: \'get\',
path: \'/some-path\',
handler: (req, res) => {
res.send(\'ok\')
}
}
]
httpServer({routes})
// Tests
import request from \'supertest\'
import { expressApp } from \'../src/app.mjs\'
describe(\'App\', () => {
it(\'should have a /health route by default\', async () => { // Test passes
const app = expressApp({ routes: [] })
const resp = await request(app).get(\'/health\')
expect(resp.ok).toEqual(true)
expect(resp.type).toEqual(\'text/html\')
expect(resp.text).toEqual(\'ok\')
})
it(\'should handle 404 requests\', async () => { // Test timeouts
const app = expressApp({ routes: [] })
const resp = await request(app).get(\'/notFound\')
expect(resp.status).toEqual(404)
expect(resp.type).toEqual(\'text/html\')
expect(resp.text).toEqual(\'No handler found for /notFound\')
})
it(\'should register all routes passed\', async () => { // Test timeouts
const routes = [{ method: \'get\', handler: (req, res) => { res.json({ value: 100 }) }, path: \'/someRoute\' }]
const server = expressApp({ routes })
const resp = await request(server).get(\'/someRoute\').send()
expect(resp.ok).toEqual(true)
expect(resp.type).toEqual(\'application/json\')
expect(resp.body).toEqual({ value: 100 })
})
}
问题是我在终端上得到 2 个不同的输出,这取决于我是否在 wath 模式下运行 jest
我试图增加开玩笑配置的超时时间,但也不起作用
\"scripts\": {
\"test:dev\": \"node --experimental-vm-modules node_modules/jest/bin/jest.js --watch --detectOpenHandles\",
\"test\": \"node --experimental-vm-modules node_modules/jest/bin/jest.js --collect-coverage --detectOpenHandles --forceExit\"
},
\"jest\": {
\"testRegex\": \"(/__tests__/.*|(\\\\.|/)(test|spec))\\\\.(mjs?|js?)$\",
\"transform\": {},
\"moduleFileExtensions\": [
\"mjs\",
\"js\"
],
\"testTimeout\": 30000 // no luck with it
}
任何想法将不胜感激......谢谢
标签: node.js express jestjs supertest