Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'selectionEnd' of null using React + Jest + Datepicker + TextMask

I had a unit test that was working, but now I added a new package to my react-datepicker, called react-text-mask and I tried to mock it, but it receive the following message when I run npm run test:

TypeError: Cannot read property 'selectionEnd' of null

at Object.update (node_modules/react-text-mask/dist/reactTextMask.js:1:9205)

at t.value (node_modules/react-text-mask/dist/reactTextMask.js:1:2431)

at t.value (node_modules/react-text-mask/dist/reactTextMask.js:1:2490)

at commitLifeCycles (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6427:22)

at commitAllLifeCycles (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7516:7)

My react-datepicker with react-text-mask:

<RCDatePicker
        {...rest}
        locale="pt-BR"
        selected={value}
        onChange={onChange}
        readOnly={readOnly}
        dateFormat={dateFormat}
        minDate={minDays ? moment(baseDate).subtract(minDays, 'days') : undefined}
        maxDate={maxDays ? moment(baseDate).add(maxDays, 'days') : undefined}
        disabled={disabled}
        customInput={<MaskedInput
          mask={[/[0-3]/, /\d/, '/', /[0-1]/, /\d/, '/', /[1-2]/, /\d/, /\d/, /\d/]}
        />}
      >

My unit test:

describe('<DatePicker />', () => {
  it('should have default props', () => {
    const mock = jest.mock('react-text-mask', () => props => <input type="text" {...{ ...props }} />);
    const tree = renderer.create(<DatePicker onChange={Function} />).toJSON()
    jest.spyOn(mock)

    expect(tree).toMatchSnapshot()
  })
})
like image 759
Felipe Augusto Avatar asked Jun 08 '18 19:06

Felipe Augusto


1 Answers

I found the solution, it was just put the mock outside the describe.

import React from 'react'
import renderer from 'react-test-renderer'
import { DatePicker } from './DatePicker'

jest.mock('react-text-mask', () => props => <input type="text" {...{ ...props }} />)

describe('<DatePicker />', () => {
  it('should have default props', () => {
    const tree = renderer.create(<DatePicker onChange={Function} />).toJSON()

    expect(tree).toMatchSnapshot()
  })
})
like image 191
Felipe Augusto Avatar answered Sep 28 '22 00:09

Felipe Augusto