javascript 中的软断言

Soft assertions in javascript

我有两个后端项目 P1 和 P2。来自 P1 的数据必须通过中间件进行一些处理后流入 P2。我正在编写这个中间件,我必须创建一个 E2E 测试模块。

我将有 100 个测试用例,每个测试用例可能有 3 或 4 个 expect 语句。 chai 'expect' 函数是硬断言的一种形式。如何在 javascript 中获得软断言。基本上,测试用例将 运行 所有 3 或 4 个 expect 语句并报告哪个失败。

Chai 不允许软断言,这违背了他们的断言哲学。尝试使用库 https://www.npmjs.com/package/soft-assert

我们需要类似的东西,而 Raymond 提出的库对我们来说还不够(我们不想更改断言库,而且该库缺少我们需要的很多断言类型),所以我写了这个我认为完美地回答了这个问题: https://github.com/alfonso-presa/soft-assert

使用这个 soft-assert 库,您可以包装其他资产库(如您要求的 chai expect),以便您可以在测试中执行软断言和硬断言。这里有一个例子:

const { proxy, flush } = require("@alfonso-presa/soft-assert");
const { expect } = require("chai");
const softExpect = proxy(expect);

describe("something", () => {
    it("should capture exceptions with wrapped chai expectation library", () => {
        softExpect("a").to.equal("b");
        softExpect(false).to.be.true;
        softExpect(() => {}).to.throw("Error");
        softExpect(() => {throw new Error();}).to.not.throw();
        try {
            //This is just to showcase, you should not try catch the result of flush.
            flush();
            //As there are assertion errors above this will not be reached
            expect(false).toBeTruthy();
        } catch(e) {
            expect(e.message).toContain("expected 'a' to equal 'b'");
            expect(e.message).toContain("expected false to be true");
            expect(e.message).toContain("to throw an error");
            expect(e.message).toContain("to not throw an error but 'Error' was thrown");
        }
    });
});