agusgambina
agusgambina

Reputation: 6699

Debbuging with Mocha and Chai ReactJS

I am trying to start writing some tests in an small app that I wrote from a React Tutorial

My Stack

node -> v8.7.0
mocha -> "^5.1.0"
jsdom -> "^11.8.0"
jquery -> "^3.3.1"
react-dom -> "^16.3.2"
react -> "^16.3.2"
chai -> "^4.1.2"
babel-register -> "^6.26.0"

Here is my test_helper

import { JSDOM } from 'jsdom';
import jquery from 'jquery';
import ReactTestUtils from 'react-dom/test-utils';
import React from 'react';
import ReactDOM from 'react-dom';
import { expect } from 'chai';

//Set up testing environment to run like a browser in the command line
const dom = new JSDOM('<!doctype html><html><body></body></html>');
global.window = dom.window;
global.document = dom.window.document;

const $ = jquery(global.window);

// Build a 'renderComponent' helper that should render a given react class
function renderComponent(ComponentClass) {
  const componentInstance = ReactTestUtils.renderIntoDocument(<ComponentClass />);

  return $(ReactDOM.findDOMNode(componentInstance));
}

//Build a helper for simulating events

//Set up chai-jquery
export { renderComponent, expect };

My board_test

import { renderComponent, expect } from '../test_helper';
import Board from '../../src/components/board';

describe('Board', () => {
  it('exist', () => {
    const component = renderComponent(Board);
    expect(component).to.exist;
  });
});

and in package.json I have

...
"scripts": {
  ...
  "test": "mocha --require babel-register --require ./test/test_helper.js --recursive ./test",
  "test:watch": "npm run test -- --watch"
}
...

When I run npm test I get this error, I understand that is related with renderComponent(...)

1) Board exist: TypeError: Cannot read property '0' of undefined

If someone want to download the project here is the link (the problem I am facing is under the branch addTests)

My Repo -> branch addTests

to change to the branch addTests

git checkout -b addTests origin/addTests

Upvotes: 0

Views: 85

Answers (1)

Bartuken
Bartuken

Reputation: 90

In your trunk

Delete your app_test in your test/component folder => (https://github.com/agusgambina/react-tic-tac-toe/tree/master/test/components).

Only if you are not using it, it seems to be a default boilerplate file

In your branch

You are testing board componenet without passing params. in your code ( not testing ) this params are passing by game component.

I suggest you to modify your helper => (test\test_helper.js) to this

function renderComponent(ComponentClass,props) {
  if (!props) props = {};
  const componentInstance = ReactTestUtils.renderIntoDocument(<ComponentClass  {...props}/>);

  return $(ReactDOM.findDOMNode(componentInstance));
}

and your board test => (test\components\board_test.js) to:

const component = renderComponent(Board, YOUR_PROPS_HERE);
expect(component).to.exist;

now you can pass props to your renderComponent

Upvotes: 1

Related Questions