Javascript 异步函数调用不工作,同步正在工作
我有一个路由器,路由如下:Javascript 异步函数调用不工作,同步正在工作,javascript,node.js,unit-testing,testing,jestjs,Javascript,Node.js,Unit Testing,Testing,Jestjs,我有一个路由器,路由如下: router.post('/login', async (req, res, next) => { try { console.log(req.body); const { username, password } = req.body; const identity = await userService.getUserInfo(username, password); if (!identity.authenticate
router.post('/login', async (req, res, next) => {
try {
console.log(req.body);
const { username, password } = req.body;
const identity = await userService.getUserInfo(username, password);
if (!identity.authenticated) {
return res.json({});
}
const requiredTenantId = process.env.TENANT_ID;
const tenant = identity.tenants.find((it) => it.id === requiredTenantId);
if (requiredTenantId && !tenant) {
return res.json({});
}
const userResponse = {
...identity,
token: jwt.sign(
identity,
envVars.getVar(envVars.variables.AUTH_TOKEN_SECRET),
{ expiresIn: '2h' }
)
};
return res.json(userResponse);
} catch (err) {
return next(err);
}
});
这基本上是一个异步函数
这是工作测试样本:
const request = require('supertest');
const user = require('../../routes/user');
describe('Test user login path', () => {
test('If authorized, it should response with authorized JWT token', () => {
request(user).
post('api/user/login/').
send({
username: 'admin',
password: 'admin'
}).
expect(200);
});
});
如果我在函数调用之前添加async并在请求之前等待用户:
test('If authorized, it should response with authorized JWT token', async () => {
await request(user).
测试将失败,并出现以下错误:
connect ECONNREFUSED 127.0.0.1:80
有人能解释为什么会这样吗?因为在路由器中我使用的是异步路由功能。这是因为supertest
希望得到一个快速应用程序,而不是路由器
您可以创建测试用途的应用程序,装载用户路由:
const app = express();
app.use(bodyParser.json());
app.use("/api/user", user);
app.listen(3000);
并将其传递给请求
await request(app)
.post("/api/user/login")