I have two backend projects P1 & P2. Data from P1 has to flow into P2 after some processing via a middleware. I am writing this middleware and I have to create an E2E testing module.
I will have 100s of test cases and in each there may be 3 or 4 expect statements. The chai 'expect' function is a form of hard assertion. How can I get soft assertions in javascript. Basically, the test case will run all 3 or 4 expect statements and report which one's failed.
I have two backend projects P1 & P2. Data from P1 has to flow into P2 after some processing via a middleware. I am writing this middleware and I have to create an E2E testing module.
I will have 100s of test cases and in each there may be 3 or 4 expect statements. The chai 'expect' function is a form of hard assertion. How can I get soft assertions in javascript. Basically, the test case will run all 3 or 4 expect statements and report which one's failed.
Share Improve this question asked Sep 26, 2018 at 10:35 sukusuku 10.9k16 gold badges78 silver badges125 bronze badges 1- maybe this could help: stackoverflow./questions/46797661/… – Sasha Commented Sep 28, 2018 at 0:30
2 Answers
Reset to default 3Chai does not allow soft asserts, it is against their assertion philosophy. Try using the library https://www.npmjs./package/soft-assert
We needed something similar and the library proposed by Raymond was not enough for us (we didn't want to change the assertion library and also the library lacks a lot of assertion types we needed), so I wrote this one that I think perfectly answers the question: https://github./alfonso-presa/soft-assert
With this soft-assert library you can wrap other assetion libraries (like chai expect that you asked for) so that you can perform both soft and hard assertions in your tests. Here you have an example:
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");
}
});
});