简体   繁体   中英

How to fail a test if no error is thrown in jest.js?

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();
    });
  });

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();
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM