React Testing: Setting up dependencies

InstructorTrevor Miller

Share this video with your friends

Send Tweet

To write tests for our React code, we need to first install some libraries for running tests and writing assertions. In this lesson we walk through setting up Mocha as our test runner and expect as our assertion library. We will also set up some React and JSX specific test tools (React Test Utils) to make writing our tests easier.

NOTE: There are many alternatives to Mocha, expect, and the other test tools we use in this course. Although we use these specific tools and libraries, the testing principles apply to all other tools.

Dean
~ 9 years ago

figure I'll post the question here.. I am running an exceedingly simple test, and it is failing here:

renderer.render(<Product />); ^

with this error:

mocha './src/**/*.spec.js' --compilers js:babel-core/register

/Users/.../node_modules/babel-core/lib/transformation/file/index.js:548 throw err; ^

SyntaxError: /Users/components/product.spec.js: Unexpected token (11:24)

I'm assuming it has to do with es6, but my app is in es6 just fine, and as you can see I have the compile with es6.

Trevor Millerinstructor
~ 9 years ago

Hey Dean, it sounds to me like you may not have babel installed? You need some sort of compiler (like Babel) that turns JSX and ES2015 code into ES5 code that Mocha can run. If you continue to have issues with Babel, you might get the best help by posting a question on Stack Overflow. Hope this helps :)

Ransyn
~ 8 years ago

Hi Trevor,

I'm using eslint, and it was flagging no-undef errors on functions such as describe() and it() in my test files. I discovered that adding the following to .eslintrc resolved it, eg : "globals": { "describe": true, "it": true }

However this doesn't feel like the most robust of solutions. Is there a better approach?

Tey Taghiyev
~ 8 years ago

Is there a way to get these running in a Codepen, specifically the test-utils. I constantly have trouble lib importing in there since you don't do 'import' and react-addons-test-utils doesnt seem to be a standalone script.

John
~ 8 years ago

A quibble (because it interferes with a lot of learning programs and ends up costing me a significant amount of backtracking). You started with step 2 -- install mocha etc. You must be explicit about step 1 because of the number of ways to get there. DId you use react-cli to create your initial project or npm init and then add the packages or create everything by hand or some other route?

PCR IT Training
~ 6 years ago

You started with step 2 -- install mocha etc.

I agree..this happens alot on Egghead.
Such a simple thing to include too...just put some written directions in the notes if you dont have it in the recording. Its a waste of time and effort to look around for how to start to get on track with the tutorial...