I
I
Igor Shumilovsky2016-08-21 16:50:26
JavaScript
Igor Shumilovsky, 2016-08-21 16:50:26

How to test such react click events in enzyme?

I have a simple button component that fires a flux action on click.

import React from 'react';
import Button from 'components/Button';

import { loginUser } from 'actions/user';

const LoginButton = () => (
  <Button onClick={() => loginUser('UserName')}>
    Войти
  </Button>
);

export default LoginButton;

How can I test that the loginUser function will be called on click? How generally to check external functions on a call? Or to score in general on such tests referring to the tests of the react itself?
I use enzyme, mocha, chai, sinon.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-08-22
@maxfarseer

Igor, I will answer your question - "how in this case to check that such and such an action is sent to the dispatcher?", Which surfaced in the comments, and which I was originally set up for =) You need to test. Everything is tested according to the documentation
. Let's analyze an example of testing an asynchronous action-creator to get a list of products: First,
the AC code (action creator)

export function getProducts() {
  return dispatch => {
    dispatch({ type: PRODUCTS_GET_REQUEST })

    return request.get(`${API_ROOT_V1}/api/v1/products/getAll`)
      .then(res => {
        if (!res.ok) {
          dispatch({ type: PRODUCTS_GET_FAILURE })
          dispatch(showNotification({
            status: 'err',
            text: 'something going wrong',
          }))

        } else {
          dispatch({
            type: PRODUCTS_GET_SUCCESS,
            data: normalize(res.body.data, schema.arrayOfProducts),
          })
        }
      }, err => {
        dispatch({ type: PRODUCTS_GET_FAILURE })
        dispatch(showNotification({
          status: 'err',
          text: err.message,
        }))
      })
  }
}

It turns out that to test the getProducts function , which is AC, we will write a test in which we expect in case of success:
a) that the store has reached the 'PRODUCTS_GET_REQUEST' event
b) that the store has reached the 'PRODUCTS_GET_SUCCESS' event with some data (I still have it normalizing , but this is not the point)
For this, we need redux-mock-store (taken also from the documentation).
Actually, the test itself:
it('creates PRODUCTS_GET_SUCCESS when get products has been done', () => {

      const data = [
        {
          '_id': '5763e6eccfdb2e9d4baa58ef',
          'name': 'Product A',
          'description': 'Description of A',
          'img': 'no-photo',
          '__v': 0,
          'providers': [],
        },
        {
          '_id': '5763e6eccfdb2e9d4baa58f0',
          'name': 'Product B',
          'description': 'Description of B',
          'img': 'no-photo',
          '__v': 0,
          'providers': [],
        },
      ]

      nock(`${API_ROOT_V1}`)
        .get('/api/v1/products/getAll')
        .reply(200, { data })

      const expectedActions = [
        { type: PRODUCTS_GET_REQUEST },
        { type: PRODUCTS_GET_SUCCESS, data: normalize(data, schema.arrayOfProducts) },
      ]

      const store = mockStore([])

      return store.dispatch(getProducts())
        .then( () => expect(store.getActions()).to.deep.equal(expectedActions) )
    })

That is, answering the question:
1) const store = mockStore([])
2) store.getActions()
3) we compare what we get in paragraph 2 with what we expect.
Here, I used nok along the way to "mock" an API request. And he described the expected "fake" date in a little more detail (although this was not necessary). The main point: we expect some "actions" to reach the store. This is what was tested.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question