Sharing Specs in Jest
Recently I decided to dive fully into testing react applications and I was hooked the moment I realized how easy it was to add specs using Jest and enzyme.
After writing specs for the app I am currently working on, I found myself in the situation of duplicating the same specs for different parts of the code over and over again.
I wanted to DRY (Don’t Repeat Yourself) my test suite up, and coming from Rails and Rspec, I was looking for something like Shared Examples but with Jest.
The idea is to move duplicated specs into shared examples and include those shared examples wherever it’s necessary.
I did’nt find a clear solution so I decided to craft my own and I thought it would be nice to share it in case someone else is in a similar situation.
So here it is:
Let’s say that your specs live inside a folder called tests
.
I created a folder called shared_examples
under tests
to store my shared specs.
In shared_examples/index.js
I added the following function:
Then I added my shared examples, for exampleaLiveBeing.js
:
Then in a spec that needs these shared examples, for examplePerson.spec.js
:
And that’s it! Now the shared specs are added and executed dynamically.
Under args
you can send different variables so your shared examples can be more customizable.
If you have a better solution I’d love to hear it!
Peace.