我有以下功能要测试:
// ...
const local = new WeakMap();
export default class User {
// ...
async password(password) {
if (!password) return local.get(this).get('hash'); // remove this for security reasons!
if (password.length < 6) throw new Error('New password must be at least 6 characters long');
if (!password.match(passwordPattern)) throw new Error(`New password must match ${passwordPattern}`);
local.get(this).set('hash', await Password.hash(password));
}
// ...
}现在,我想用摩卡咖啡、印度茶和柴应生来测试这个函数:
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import User from '../../../server/User';
chai.use(chaiAsPromised);
const expect = chai.expect;
describe('.password()', () => {
const testuser = new User({username: 'Testuser', password: '123abc'});
// FINDME
it(`should throw when too short`, () => {
return expect(testuser.password('1a')).to.eventually.throw();
});
// ...
});查找上面代码中的// FINDME注释,以获得我所指的上下文。
因此,测试不会等待异步password()函数完成。正如我发现的那样,ECMAScript7异步函数会立即返回一个可处理的函数,所以它应该是可以的,因为chai承诺使用这个特性。我的猜测是,异步函数不会向上述承诺中抛出错误,而不会将其抛到封闭函数本身中,无法通过expect()捕获它。
对于急切的人们:我使用以下命令动态地使用巴贝尔传递这段代码:
babel-node --experimental node_modules/mocha/bin/_mocha --watch --recursive -R spec --check-leaks
更新Babel 6:
使用babel-node 6.4.0,可以使用以下方法:
npm install --save-dev babel-preset-stage-0然后跑:
./node_modules/.bin/babel-node --presets stage-0 node_modules/mocha/bin/_mocha --
recursive -R spec --check-leaks发布于 2015-04-05 11:30:21
我们解决了这个问题,将eventually.throw()替换为chai承诺提供的.be.rejected,因为async function总是返回承诺。我一开始还不清楚。如果您愿意的话,请看一下关于github的讨论。
https://stackoverflow.com/questions/29334775
复制相似问题