Extend Vitests API with custom expects

Extend Vitests API with custom expectsReusable things like the coffee cups in my title are not just good in real life. Having reusable code is also key in software development. In this short article, I will give you another handy tool to write your test code more reusable. You will learn how to extend Vitests API to exactly fit your needs by writing custom expects. A way to write reusable assertions, usable in the same way as _toBe()_. So let's get started!
Categoriesvitest javaScripttesting
Date
2022-07-19
Hire me on Upwork!

What is Vitest

Vitest is the brand new, superfast test runner you should know in 2022!

If you heard from it the first time, you can also check out the Docs or my Vitest UI review here.

Why do I need a Custom expect in vitest?

Why do I require a bike? I can also go from A to B on my feet. But with a Bike, I can drive from A to B way faster, and way more comfortable.

You can add custom expects in vitest how you may be already familiar with jest.

With this handy feature, you can customize your tests and write better, more readable assertions.

Let's think of testing some calculations, as an Oracle you will probably have done some calculations by hand and compare them against your SUT.

For example, we are having a circle and want to calculate its area.

Depending on how your software calculates Pi and how your Oracle has been using Pi, you will get different results. Maybe you are crazy and estimated Pi with 3.14, but your method is going way more into detail and using it with 10+ coma values. (Just a simple example to visualize rounding errors).

Most of your tests will probably fail. You will have to round the result before each comparison.

Imagine you are having this case 100 times, you will end up with 99 code duplicates.

You still want to use the data provided by the oracle. So we need a way to give it a tolerance without having to round the result in each test. That's the use case for a custom expect in vitest!

How to create a custom expect in vitest?

Given the example above, you could possibly chain toBeGreaterThan and ToBeLowerThan together, but you would have to do this in all of your tests.

Or, Which is way more elegant, you can simply write your own custom expect and extend the default ones with it.

Below there is the example code for toBeInTolerance.

    expect.extend({
          toBeInTolerance: (received, expected, tol) => {
            console.log("toBeInTolerance called with:", received, expected, tol);
            if (received < received - tol || received > received + tol) {
              return {
                message: () => `expected ${received} to be ${expected} +/- ${1} `,
                pass: false,
              };
            } else {
              return {
                message: () => `the-koi is awesome!`,
                pass: true,
              };
            }
          },
        });

Conclusion

You have the power to customize vitests assertions to exactly fit your needs. You can come up with way more examples that will improve your test writing pace a lot and reduce painful things like deep checking huge complex objects to match a specific structure.

If they occur more than once in your tests, just write a custom expect to do the job.

You could also extend the already provided assertions to give you more details about the assertion, build fluent assertions, write into log files. You name it.

There is really no limit to your creativity, go ahead and try it out!

I hope I could speed up your testing process with this short article.

Happy asserting,

Alex.

Recommended Products for you
recommended for you