如何多次调用断言直到它为真?

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

假设我得到了一些基本断言,如下所示:

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

myObject.getValue() 的返回值应该是 5 在其他地方的几个代码 运行 之后,所以我只需要让这个 value 更新.

我的问题是,创建这种测试的代码是什么?

Mocha 有 retrying tests 的功能。您可以在测试中使用 this.retries(number_of_tries)。像这样:

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

如果要设置整组测试的重试次数,也可以在 describe 块中使用它。请注意,如果您使用 this.retries,它不能出现在箭头函数 (() => ...) 中,因为箭头函数让 this 保持它在箭头函数出现的范围内的值。您必须使用完整功能 (function () ...)。

为了更精确地重试什么,请使用 retry-assert 库:

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

在编写更高级别的功能测试时重试整个测试过于粗粒度 - 例如在测试具有异步状态更改的 API 时 - 而不是 CucumberJS 的选项。 Retry Assert 适用于任何测试运行程序,并且会在您重试断言失败次数过多时给出有意义的错误消息。

免责声明:我是 retry-assert 的作者。