dimanche 31 juillet 2016

How to create Chai/Mocha unit tests for a ES6 class React component?

I'm having trouble creating Chai/Mocha unit tests for an ES6 class. This project is configured correctly to use chai/mocha, ES6, babel, so that's not the issue. (I can run a dummy test where I check if 2 variables are the same). The error only throws when I try to use the ES6 class React component below. I run the test using the command npm test. My package.json is configured to run this command when I run npm test:

mocha --compilers js:babel/register file/path/to/spec --recursive

I am getting this error:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the component

The ES6 class React component that looks like (obviously not all of it):

import ...

class Car extends React.Component {
  constructor() {
    super();
    this.state = {
      color: ''
    }
  }

  setColor(color) {
     this.setState({ color : color });
  }

  render() {
    .......
  }
}

The test/spec JS file looks (mostly like):

import ...

let should = chai.should();
describe('Car Test', () => {
  let car;

  beforeEach(() => {
    car = new Car();
  });

  it('should be red', () => {
    car.setColor('red'); // pretty sure THIS is throwing the error
  });
});

Aucun commentaire:

Enregistrer un commentaire