Home > Back-end >  How to fail a test if no error is thrown in jest.js?
How to fail a test if no error is thrown in jest.js?

Time:06-15

i'm currently improving the branch/function coverage of our feathers.js/node.js api (testing with jest). Currently there is a service with a property which should only accept certain values, which is not implemented yet.

Valid values would be something like:

const validValues = ["System", "Engineering", "Production"]

If one of the values is provided, the api should accept the request and return a valid response.

If a value like

const invalidValue = ["Some", "Invalid", "Value"]

is provided, the API should reject the request.

Since value validation is not implemented yet, the idea was to implement a test which fails if invalid values like which are accepted by the api and it is ensured that the api only accepts valid values.

it("test service for invalid values", async () => {
    const invalidValues = ["Some", "Invalid", "Value"];

    invalidValues.map(async (invalidValue) => {
      await expect(async () => {
        await app.service("release-types").create({
          someProperty: "some Value"
          propertyWithValueConstraint: invalidValue,
        });
      }).rejects.toThrow();
    });
  });

CodePudding user response:

The problem is that [].map does not run asynchronously and therefore does not catch the assertions. You have two options:

  1. Use await Promise.all(promises):
it("test service for invalid values", async () => {
  const invalidValues = ["Some", "Invalid", "Value"];

  await Promise.all(invalidValues.map(async (invalidValue) => {
    await expect(async () => {
      await app.service("release-types").create({
        someProperty: "some Value"
        propertyWithValueConstraint: invalidValue,
      });
    }).rejects.toThrow();
  }));
});
  1. Use a for ... of loop
it("test service for invalid values", async () => {
  const invalidValues = ["Some", "Invalid", "Value"];

  for (const invalidValue of invalidValues) {
    await expect(async () => {
      await app.service("release-types").create({
        someProperty: "some Value"
        propertyWithValueConstraint: invalidValue,
      });
    }).rejects.toThrow();
  }
});
  • Related