Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spy on setState and test toHaveBeenCalled() using jest

Tags:

reactjs

jestjs

Using Jest and React, How do I spy one this.setState() and test weather the function hasBeenCalled()

it('shall update targets when engine register has been called', () => 
{
  const wrapper = shallow(
    <LazyloadProvider>
      <p>Wow</p>
    </LazyloadProvider>
  ).instance();
  expect(wrapper.state.targets).toEqual({}); // pass
  wrapper.engine.register(FIXTURE.REACT_REF); // pass
  expect(wrapper.state.targets).not.toEqual({}); //pass
  expect(wrapper.setState).toHaveBeenCalled(); // fail
});

Engine Getter:

  get engine() {
    return {
      state: this.state,
      register: target => {
        this.setState(LazyloadUtils.registerOneTarget(target));
      },
    };
  }
like image 261
Armeen Harwood Avatar asked Oct 10 '18 19:10

Armeen Harwood


People also ask

How do you test for useState hook in jest and enzyme?

Testing the useState Hook with Enzyme import React from "react"; const App= () => { const [name, setName] = React. useState(""); return ( <form> <div className="row"> <div className="col-md-6"> <input type="text" placeholder="Enter your name" className="input" onChange={(e) => { setName(e.

How do you mock useState in jest test?

To enable us to mock useState, we use React. useState (line #5) instead of using the usual named import (i.e. import { useState } from 'react'). Below is our Jest unit test for the component. Before rendering the component for testing, we create a constant 'setStateMock' and mock it with a jest function jest.


2 Answers

Ideally, you'd want to check for the key in state object that your setState method is updating

expect(wrapper.state('foo')).toEqual('bar')

IF you really want to spy on the method itself, you can mock the setState method on the component prototype. You would need to do this before creating a shallow copy of your component.

it('shall update targets when engine register has been called', () => 
 {
   LazyloadProvider.prototype.setState = jest.fn();
   const wrapper = shallow(
      <LazyloadProvider>
        <p>Wow</p>
      </LazyloadProvider>
    ).instance();
   expect(wrapper.setState).toHaveBeenCalled();
 }
like image 91
Pranita Avatar answered Oct 22 '22 07:10

Pranita


if you want to continue testing after the call to setState, you should spy, not mock the method

it('shall update targets when engine register has been called', () => 
 {
   const setStateSpy = jest.spyOn(LazyloadProvider.prototype, 'setState');
   const wrapper = shallow(
      <LazyloadProvider>
        <p>Wow</p>
      </LazyloadProvider>
    ).instance();
   expect(setStateSpy).toHaveBeenCalled();

   // write more tests that want the dom to update
 }
like image 40
mlg87 Avatar answered Oct 22 '22 06:10

mlg87