AllenFang / react-bootstrap-table

A Bootstrap table built with React.js
https://allenfang.github.io/react-bootstrap-table/
MIT License
2.23k stars 782 forks source link

Jest snapshot tests result in Type error #1160

Open ndrewr opened 7 years ago

ndrewr commented 7 years ago

First off kudos for this rather fun-to-use component :)

OK so the issue I am bumping into happens when I set up a snapshot test with Jest and react-test-renderer.

The test file is essentially:

import renderer from 'react-test-renderer';
import Table from '../Table';

it('matches the Table snapshot', () => {
    var component = renderer.create(
      <Table data={testData} columns={columns} />
    );

    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });

(Note the Table component is just a wrapper that defines some basic BootstrapTable props.)

And when running tests, I am alerted to this (partial stack trace):

 TypeError: Cannot read property 'setAttribute' of null

      at TableHeaderColumn.componentDidMount (../node_modules/react-bootstrap-table/lib/TableHeaderColumn.js:138:30)
      at ../node_modules/react-test-renderer/lib/ReactCompositeComponent.js:265:25

which points back to this line in TableHeaderColumn / ComponentDidMount:

 value: function componentDidMount() {
      this.refs['header-col'].setAttribute('data-field', this.props.dataField);
    }

Anyone else encounter this?

Am I doing something wrong? Apologies if should I be asking somewhere else on this; have been bouncing around Jest and React repos as well as here.

mvolkmann commented 7 years ago

I am hitting the same problem in a Jest test.

AllenFang commented 7 years ago

sorry for lately reply, I'll do some investigation.

dangreenisrael commented 7 years ago

I think I found a workaround, enzyme and enzyme-to-json

After getting the same error, I tried this method and it worked (<PayrollReport> uses React Bootstrap Table)

import React from 'react';
import toJson from 'enzyme-to-json';
import {shallow} from 'enzyme';
import PayrollReport from '.';
import data from './__testData__/testData';

test('PayrollReport Renders Correctly', () => {
  const wrapper = shallow(<PayrollReport data={data} />);
  expect(toJson(wrapper)).toMatchSnapshot();
});
Snaptags commented 6 years ago

The workaround didn't really help in my case, because I got snapshots only containing . That way the test would ALWAYS succeed ...

My workaround uses nothing but Jest!

Jest will be replacing all TableHeaderColumn components by tableHeaderColumnMock then, successfully rendering a reasonably well representation of the page.