gpt4 book ai didi

Javascript 规范 : promises chains and omitted expectations

转载 作者:行者123 更新时间:2023-11-28 21:09:24 26 4
gpt4 key购买 nike

考虑以下规范:

describe('User', () => {
it('requires username', done => {
factory.build('user', { username: '' })
.then(user => user.validate())
.catch(error => expect(error.errors.messages.username).toMatch('is required'))
.then(done);
});
});

在这种情况下,如果创建成功,则不会调用 catch 回调,我们就完成了。所以基本上规范成功而它应该失败。这只是一般问题的一个示例:当我们将期望放在 then/catch 中时,我们无法确定它们是否会被调用。

你会怎么写这个?

对于这个具体示例,我可以想到这样的解决方案(但我不喜欢以这种方式将回调与 promise 混合):

describe('User', () => {
it('requires username', done => {
factory.build('user', { username: '' })
.then(user => user.validate(error =>
expect(error.errors.messages.username).toMatch('is required')))
.then(done);
});
});

最佳答案

如果您不希望发生这种情况,您会抛出一个错误:

return factory.build('user', { username: '' })
.then(user => user.validate())
.then(result => { throw new Error("expected rejection but got fulfilled promise"); },
error => expect(error.errors.messages.username).toMatch('is required'))

或者,您可以手动或使用 promise 方法(例如 reflect)将这两种情况转换为匹配的结果值。 :

  .then(result => null,
error => error)
.then(val => expect(val.errors.messages.username).toMatch('is required'))

如果您知道 result 绝不是类似错误的对象,您可以省略第一个 onFulfilled 回调或只使用 catch

关于Javascript 规范 : promises chains and omitted expectations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39354490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com