close

From: http://www.hackingwithreact.com/read/1/32/how-to-configure-jest-to-test-react-and-es6

--------------------------------------

How to Configure Jest to Test React and ES6

To get started, we need to add some extra development dependencies by running this command in a terminal window:

npm install --save-dev jest-cli babel-jest react-addons-test-utils

As before, you'll need to press Ctrl+C to quit Webpack Dev Server before you run that, but this time I don't want you to restart Webpack Dev Server when the npm command finishes. We're done with it – it's all testing now!

We're going to start our tests in a new subdirectory of our project. We already have dist for our finished files, node_modules for all the NPM things we use, and src for our ES6 source code. But I want you to create a fourth folder now:

mkdir __tests__

That's two underscores, the word "tests", then two more underscores. Please name it exactly that otherwise your tests will not work. With that done, we're going to modify our package.json file so that it knows to call Jest when we ask it to run tests. Open your package.json file now and you'll see a line like this:

package.json

"test": "echo \"Error: no test specified\" && exit 1"

Please change it to this:

package.json

"test": "jest --verbose"

While you're there, we need to insert some configuration settings to enable Jest to work with React and ES6. Look for "devDependencies" and put this directly before it:

package.json

"jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "unmockedModulePathPatterns": [
        "<rootDir>/node_modules/react",
        "<rootDir>/node_modules/react-dom",
        "<rootDir>/node_modules/react-addons-test-utils",
        "<rootDir>/node_modules/fbjs"
    ]
},

The final version should look like this:

package.json

{
    "name": "hwr",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "jest --verbose"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "babel": {
        "presets": [
            "es2015",
            "react"
        ]
    },
    "jest": {
        "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
        "unmockedModulePathPatterns": [
            "<rootDir>/node_modules/react",
            "<rootDir>/node_modules/react-dom",
            "<rootDir>/node_modules/react-addons-test-utils",
            "<rootDir>/node_modules/fbjs"
        ]
    },
    "devDependencies": {
        "babel-core": "^6.7.2",
        "babel-jest": "^9.0.3",
        "babel-loader": "^6.2.4",
        "babel-preset-es2015": "^6.6.0",
        "babel-preset-react": "^6.5.0",
        "jest-cli": "^0.9.2",
        "react-addons-test-utils": "^0.14.7",
        "react-hot-loader": "^1.3.0",
        "webpack": "^1.12.14",
        "webpack-dev-server": "^1.14.1"
    },
    "dependencies": {
        "chance": "^1.0.1",
        "history": "^2.0.1",
        "react": "^0.14.7",
        "react-dom": "^0.14.7",
        "react-router": "^2.0.1",
        "superagent": "^1.8.0"
    }
}

With that change saved, we can now run our test through Jest by running this command:

npm run test

Of course it doesn't actually do anything yet other than print its version number, because we haven't written any tests. Let's do that now…

Running Jest without any tests is a good idea if only to make sure you have it set up correctly.

 

Creating our First React Test with Jest

The reason we had to name our test directory tests is because that's exactly what Jest looks for when it runs its test process: all JavaScript files in there are considered tests and will be executed.

So, we can put a very simple test into that folder, and npm run test will automatically find it, run it, and tell us the results. Let's start with an extremely simple test: does our List component render three repositories for users to click on?

Now, you probably think that's a silly thing to test because we can see it always renders exactly three repositories. But that's OK; you're just learning, and this is a bit of a forced example to help you get started. Create a new file in the tests directory called List-test.js and give it this content:

__tests__/List-test.js

jest.autoMockOff();

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';

const List = require('../src/pages/List').default;

describe('List', () => {
    it('renders three repo links', () => {
        const rendered = TestUtils.renderIntoDocument(
            <List />
        );

        const repos = TestUtils.scryRenderedDOMComponentsWithTag(rendered, 'li');

        expect(repos.length).toEqual(3);
    });
});

That's almost all new code so I want to explain it all to you. But first, save that file then run the test by using npm run test. You should see output like this:

Using Jest CLI v0.8.2, jasmine1
 PASS  __tests__/List-test.js (1.036s)
List
  ✓ it renders three repo links

The test was successful! That's no great surprise, as I already said, but at least it shows you have Jest set up correctly.

Let's talk through all the code in that file, because you've seen only a few lines of it before:

  • jest.autoMockOff() Disables one of Jest's most powerful features, known as mocking. Without this line, Jest will silently replace any library we try to use with a fake version suitable for testing. This is extremely helpful when you're past beginner status, but right now it's just going to confuse you so we turn it off.
  • import TestUtils from 'react-addons-test-utils'; React's test utility library gives us the ability to render React components into a fake document that can then be checked to make sure it looks how we think it ought to.
  • const List = require('../src/pages/List').default loads our List component. This is an annoyance related to the way Babel and Jest work together and does the same as our previous import List from './pages/List' code.
  • describe('List', () => { starts a test suite, which is a group of related tests. In this tutorial we'll have one test suite per React component.
  • it('renders three repo links', () => { starts a test spec. Each test spec has a description ("renders three repo links") and some code attached to it (everything after the {).
  • const rendered = TestUtils.renderIntoDocument converts some JSX into a virtual document that we can examine. We pass in <List /> so that it renders our List component.
  • const repos = TestUtils.scryRenderedDOMComponentsWithTag(rendered, 'li') searches through our virtual document for all <li> elements, and returns them in an array.
  • expect(repos.length).toEqual(3) checks that the number of <li> elements that were found matches the number 3 – i.e., that three <li> elements exist on the page.

That's a raw description of what the code does, but three things deserve further clarification.

First, Jest encourages you to use natural language to express what you're trying to test and why. This is part of the behavior-driven development approach, and it's important because it forces you to focus on what you're trying to test rather than how it works. So, we can read each test out loud: "it renders three repo links".

Second, the method scryRenderedDOMComponentsWithTag() has a curious name. "Scry" (which rhymes with "cry", if you were wondering) is an archaic word meaning "to gaze into a crystal ball", i.e. fortune telling. Clearly hipsters are intent on making it cool once more, so you can scry into your rendered document to look for things.

Third, we tell Jest what we expect to happen using its expect() function. Again, this is designed to be read aloud like plain English: "expect repos length to equal 3." If this expectation is matched (i.e., if our component outputs three repos) then the test is considered a success. Any variation from the expected result is considered a test failure.

We're using Jest with the --verbose option, which provides more detailed feedback on each test it runs.

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Foxbrush 的頭像
    Foxbrush

    Foxbrush

    Foxbrush 發表在 痞客邦 留言(0) 人氣()