0

I was surprised that many blogs are writing unit tests for React Applications using both Jest and Enzyme. Cant, we write unit tests for React applications by using the only jest or by the only Enzyme??

If yes, to get a component we use shallow() in enzyme but what we use in Jest?

1

2 Answers 2

2

I think you didn't fully understand the concepts of jest and enzyme.

Jest

TL;DR: Jest is just a test runner on steroids for JavaScript (not just react).

The main functionality of jest is to execute JavaScript tests. It gives you tools to organize your tests, e.g. using describe, it or test blocks. jest comes with a lot of build-in assertions (e.g. expect(actual).toBe(expected)) to help you identifying failing and succeeding tests. On top of that jest comes with additional features, for example it allows you to easily mock functions or even complete modules.

jest is not bound to react in general, but does quite well in combination with react, since it is maintained by facebook just as react itself. So it's basically almost everytime the right joice and also recommended by react.

Enzyme

TL;DR: Collection of utilities to simplify testing/rendering react components.

Technically you don't need Enzyme or any other framework to test react components (only jest). react already exposes react-dom/test-utils but it's really cumbersome to work with those without properly wrapping and simplyfing its API. And that's exactly what enzyme is doing. It basically puts a layer of abstraction over react-dom/test-utils and adds a bunch of utilities, so you don't need to worry about implementing them yourself.


I highly recommend you to look at react-testing-library, an alternative to enzyme, and read "Testing Implementation Details" blog post authored by its founder. react-testing-library is, like jest, recommended by react.

Sign up to request clarification or add additional context in comments.

Comments

1

Jest and Enzyme are not comparable.

Jest don't give you rich API/function to access dom elements like enzyme but it does other important tasks like when you hit command npm test or npm run test jest collect all the test file eg all files ending with .test.js run each test cases within these files and show the result in the console like below its jest responsibility.

enter image description here

Jest is a testing framework or test runner which runs all the test files in one go, enzyme is a utility or library consider this a smaller thing compare to jest it gives many functions to access dom easily like shallow, mount, find, children, etc...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.