menu

Testing Library

Simple and complete DOM testing utilities that encourage good testing practices.

Channels
Chat
view-forward
# All channels
view-forward
# General
view-forward
# General Help
view-forward
# Angular Help
view-forward
# Cypress Help
view-forward
# DOM Help
view-forward
# React Help
view-forward
# Svelte Help
view-forward
# TestCafe Help
view-forward
# Vue Help
view-forward
Team

How to mock setState?

February 3, 2020 at 10:48am

How to mock setState?

February 3, 2020 at 10:48am
my event handler change state by using setState I need to mock how can I do that?

February 3, 2020 at 10:53am
I don't think this is the philosophy you should follow for testing things with testing-library. Instead of mocking setState, you should simulate in your component what your user would do through the UI and then check corresponding elements are present/not present, have proper value etc. This tweet from Ryan Florence sums up this philosophy perfectly https://twitter.com/ryanflorence/status/1127251480098983936
like-fill
1
  • reply
  • like
If you have very complex state transitions that you cannot simplify and you definitely want to test them - try using the function-based setState (see the React docs about setState) and extract the function you are passing as an argument to setState call - then unit-test it with Jest :)
like-fill
1
  • reply
  • like