How to call assert for several time until it's true?

别来无恙 提交于 2020-05-19 04:51:03

问题


Say that I got some basic assert as below:

expect(myObject.getValue()).to.equal(5);

And the returned value from myObject.getValue() should be 5 after several code running over some other place, so I just need to let this value to be updated.

My question is, what is the code for creating this kind of test?


回答1:


Mocha has a facility for retrying tests. You can just use this.retries(number_of_tries) in your test. Like this:

it("something", function () {
    this.retries(10);
    expect(myObject.getValue()).to.equal(5);
});

You can also use it in a describe block if you want to set the number of retries for an entire set of tests. Note that if you use this.retries, it cannot appear in an arrow function (() => ...) because arrow functions let this remain the value it had in the scope in which the arrow function appeared. You must use a full function (function () ...).




回答2:


For greater precision over what is being retried use the retry-assert library:

const activeUser = await retry()
    .fn(() => getUser(id))
    .until(user => expect(user).toHaveProperty('active', true))

Retrying the entire test is too coarse grained when writing higher level functional tests - for example when testing APIs that have asynchronous state changes - and is not an option with CucumberJS. Retry Assert works with any test runner and will give meaningful error messages when your retried assertion fails too many times.

Disclaimer: I'm the author of retry-assert.



来源:https://stackoverflow.com/questions/42386037/how-to-call-assert-for-several-time-until-its-true

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!