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
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.
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.