Funk Soul Ninja Funk Soul Ninja - 11 days ago 10
React JSX Question

React component test keeps failing

I keep getting this error when testing my TodoList component:


debug.html:38

Invariant Violation:

Element type is invalid:

expected a string (for built-in components) or a class/function (for composite components) but got: object.


I'm not sure what's causing it. Could anyone lead me into the right direction?

TodoList.js:

import React from 'react';

import Todo from 'Todo';

class TodoList extends React.Component {
renderTodos(todos) {
return todos.map(todo => {
return <Todo key={todo.id} {...todo} />;
});
}
render() {
const { todos } = this.props;
return (
<div>
{this.renderTodos(todos)}
</div>
);
}
}

export default TodoList;


TodoList.test.js:

const React = require('react');
const ReactDOM = require('react-dom');
const TestUtils = require('react-addons-test-utils');
const expect = require('expect');
const $ = require('jQuery');

const TodoList = require('TodoList');
const Todo = require('Todo');

describe('TodoList', () => {
it('should exist', () => {
expect(TodoList).toExist();
});

it('should render one Todo component for each todo item', () => {
const todos = [{
id: 1,
text: "Do something"
}, {
id: 2,
text: "Check mail"
}];
const todoList = TestUtils.renderIntoDocument(<TodoList todos={todos} />);
const todoComponents = TestUtils.scryRenderedComponentsWithType(todoList, Todo);

expect(todoComponents.length).toBe(todos.length);
});
});


Link to source code: link to source code

Answer

In your TodoList.Test.js, remove

const TodoList = require('TodoList');
const Todo = require('Todo');

and replace it with

import TodoList from 'TodoList'
import Todo from 'Todo

That is because you are exporting your components in the ES6 way and importing it the nodejs way.

If you still want to use require in your test then you will have to replace the

export default TodoList

with

module.exports = TodoList;

Hope it helps :)