DEV Community

Avinash Maurya
Avinash Maurya

Posted on

Jest Node.js and React

Here's a Jest cheat sheet summarizing its key features for writing effective unit tests in your Node.js and React projects:

1. Test Structure:

  • it function: Defines a single test case.
    • describe block (optional): Groups related test cases.
describe("MyComponent", () => {
  it("should render correctly", () => {
    // Your test code here
  });
});
Enter fullscreen mode Exit fullscreen mode

2. Matchers:

  • Basic matchers:
    • toBe: Checks strict equality (===)
    • toEqual: Checks deep equality (regardless of object structure)
    • toBeNull
    • toBeUndefined
    • toBeTruthy
    • toBeFalsy
  • Number matchers:
    • toBeGreaterThan
    • toBeLessThan
    • toBeCloseTo (allows for a precision parameter)
  • String matchers:
    • toContain (checks if a substring exists)
    • toMatch (checks for a regular expression match)
  • Array/Object matchers:
    • toContainEqual (checks if an array contains all elements in another array)
    • toMatchObject (checks if an object contains all properties and values in another object)

3. Mocking:

  • jest.fn(): Creates a mock function for testing dependencies.
  • Mock assertions:
    • toHaveBeenCalled: Checks if the function was called.
    • toHaveBeenCalledWith: Checks if the function was called with specific arguments.
    • toHaveReturnedWith: Checks the function's return value.

4. Snapshot Testing:

  • toMatchSnapshot: Takes a snapshot of a value and compares it to a previously saved snapshot.
  • Useful for ensuring UI components render consistently.

5. Async/Await Testing:

  • Jest supports both async/await syntax and the callback approach with done for asynchronous testing.

Additional Resources:

Remember, this is a concise overview. Refer to the official documentation for in-depth information and examples for each feature.

Top comments (0)