React-number-format: How to uint test NumberFormat using Jest and Enzyme?

Created on 10 Jan 2019  路  2Comments  路  Source: s-yadav/react-number-format

Hello,

I'm trying to unit test a component that uses the NumberFormat component. The unit test fails with the following error: "TypeError: el.focus is not a function".

Example code for the test:

import React from 'react';
import {mount} from 'enzyme';
import NumberFormat from 'react-number-format';

describe('NumberFormat', () => {
  it('<input>, onChange - WORKS', () => {
    const spy = jest.fn();
    const wrapper = mount(
      <div>
        <input
          value="8"
          id="fn1"
          onChange={spy}
        />
      </div>
    );
    const cb = wrapper.find('input');
    cb.simulate('change', {target: {value: '9'}});
    expect(spy).toHaveBeenCalled();
  });

  it('<NumberFormat>, onChange - FAILS', () => {
    const spy = jest.fn();
    const wrapper = mount(
      <NumberFormat
        value={1001.2}
        thousandSeparator=" "
        decimalSeparator=","
        decimalScale={2}
        fixedDecimalScale
        id="fn1"
        onChange={spy}
      />
    );
    const cb = wrapper.find('input');
    cb.simulate('change', {target: {value: '9'}}); // Fails on this stmt
    expect(spy).toHaveBeenCalled();
  });
});

What is the correct way to set up a unit test to simulate onChange/onValueChange ?

Regards
Leif Olsen

Most helpful comment

Just solved this myself.

Replace: cb.simulate('change', {target: {value: '9'}}); with...

cb.simulate('change', {target: {value: '9', focus: () => {}}});

Basically just add an empty focus function.

All 2 comments

Just solved this myself.

Replace: cb.simulate('change', {target: {value: '9'}}); with...

cb.simulate('change', {target: {value: '9', focus: () => {}}});

Basically just add an empty focus function.

@sross0988 solution worked great with the inputs which are empty initially, but not with inputs with has some default value in it.
So i firstly set value to '' and then set to expected value to make it run correctly for the prefilled inputs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

havantuan picture havantuan  路  7Comments

sezarthiago picture sezarthiago  路  7Comments

ddmedeiros picture ddmedeiros  路  6Comments

arpontes picture arpontes  路  7Comments

luis-carlos-campos picture luis-carlos-campos  路  3Comments