React Unit Test Code Snippets with Jest and Enzyme

Sometimes all I need is to see a snippet of code without much explanation when I try to find a solution online. This is because I am familiar enough with the language and framework and need a quick reminder. So, here it is. I created a post with a few React unit test code snippets with Jest and Enzyme.

List

  • Snapshot testing
  • Testing to see if a DOM element exists
  • Testing to see if a class exists in the specific DOM element
  • Testing to see if an element has the correct value
  • Simulating button click event and its outcome
  • Checking function has been called once
  • Checking function has been called with a specific argument

Testing React Form

Check out the post here. It has a little bit more focus on React form unit testing. You can check out the complete solutions here: react-form-unit-test-example.

Reference

For Enzyme, I check this cheatsheet all the time. For style, I often refer React style guide from Airbnb.

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …