Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable React's CSSTransitionGroup in test

I'm using CSSTransitionGroup to animate an element when it appears in the DOM, or when it leaves the DOM. It works well.

Now - I want to unit test this component. I'm creating a temporary DOM node and I attach it to the <body>, I render my component into it, and then I perform some actions. As a result, I expect a child DOM node to disappear.

The problem: Animation classes are applied, and component is kept in the DOM until CSS animations end. This means my test should also wait for a few hundred milliseconds before I can assert for that element being gone. I cannot do that - I want my tests to be fast, as those are unit tests.

The question: Is there a way to disable CSS transitions without adding extra options to my component?

What I tried: Unit testing itself works well. I can get rid of animations by passing a parameter to my component that will make it not use CSSTransitionGroup. So - worst case scenario - I'll do just that. But I'm looking for a better solution.

I could also assert that "-enter"/"-enter-active"/"-leave"/"-leave-active" classes are present on an element in question. That seems a bit hacky though, as I could imagine a bug where those classes would be applied, but element would remain in the DOM. I'd prefer not to resort to this approach.

like image 340
kamituel Avatar asked Apr 11 '16 13:04

kamituel


1 Answers

Using Jest this is the solution I came up with. I mocked the Transition component. Since my import looks like import {Transition} from 'react-transition-group' this is what I created:

Based on my jest config, anything found in my __mocks__ folder is used instead of any imports.

__mocks__/react-transition-group/index.js:

import Transition from './Transition'

export { Transition }
//more exports to come as I use other parts of react-transition-group

__mocks__/react-transition-group/Transition.js:

import React from 'react'

export default (props) => (
  <div>
    {props.in ? props.children() : null}
  </div>
)

This way, children is immediately rendered - the "Transition" is pretty much disabled.

**This works for v2.4.0 of react-transition-group

like image 63
Joao Avatar answered Sep 16 '22 12:09

Joao