以下应该可以正常工作。我添加了异步,因为send
可以异步调用:
const createResponse = () => {
var resolve;
const p = new Promise(
(r,reject)=>resolve=r
);
return [
{
send: (value) => {
resolve(value)
}
},
p
];
};
test('(async) fail', done => {
//Router
const router = express.Router();
//Endpoint to fetch version
router.get('/api/version', (req, res) => {
setTimeout(x=>res.send('v1'),10)
});
const request = {
method: 'GET'
};
let [response,p] = createResponse()
router.stack[0].handle(request, response, () => {});
p.then(
x=>expect(x).toBe('v2'),
reject=>expect("should not reject").toBe(reject)
).then(
x=>done()
//,x=>done() //this will cause all tests to pass
);
});
在评论中回答您的问题;考虑以下代码:
const express = require('express');
const router = express.Router();
//Endpoint to fetch version
router.get('/api/version', (req, res) => {
res.send("Hello World");
});
const request = {
method: 'GET'
};
const response = {
send: (value) => {
debugger;//pause here and see the stack
throw new Error("Hello Error.");
}
};
router.stack[0].handle(
request,
response,
//this is the function done in route.js:
// https://github.com/expressjs/express/blob/master/lib/router/route.js#L127
err => {
console.error(err.message);//console errors Hello Error.
}
);
Send 抛出一个错误,但是你的模拟调用了 send ,这里的 express 调用了它。所以 express 捕获了异常,然后在这里结束(done
不仅仅是来自你的回调)。
所以它会用错误调用你的回调,done
从 jist 中跳过而不抛出任何东西(可能在日志中显示一些东西)。由于您的回调没有做任何事情,所以它会超时。
您可以尝试在回调 (at )done
中从 jist 调用。console.error(err.message);
[更新]
仔细尝试捕获expect
以下引发的错误将告诉我 1 次测试通过:
test('(async) fail', done => {
try{
expect(true).toBe(false);
}catch(e){
}
done();
});