官术网_书友最值得收藏!

Writing a failing test

What exactly is a test? We'll discover that by writing one. In your project directory, type the following commands:

mkdir test
touch test/Appointment.test.js

Open the test/Appointment.test.js file in your favorite editor or IDE and enter the following:

describe('Appointment', () => {
});

The describe function defines a test suite, which is simply a set of tests with a given name. The first argument is the name (or description) of the unit you are testing. It could be a React component, a function, or a module. The second argument is a function inside of which you define your tests.

All of the Jest functions are already required and available in the global namespace when you run the npm test command. You don't need to import anything.

For React components, it's good practice to give your describe blocks the same name as the component itself.

You should run this code right now in the Jest test runner. It will give us valuable information about what to do next. You might think that running tests now is pointless, since we haven't even written a test yet, but with TDD, it's normal to run your test runner at every opportunity.

On the command line, run the npm test command:

> appointments@1.0.0 test /home/daniel/work/react-tdd/ch1
> jest

FAIL test/Appointment.test.js
● Test suite failed to run

Your test suite must contain at least one test.

at node_modules/jest/node_modules/jest-cli/build/TestScheduler.js:225:24

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.917s
Ran all test suites.
npm ERR! Test failed. See above for more details.

You can see Jest helpfully tells us Your test suite must contain at least one test. Test-driven developers rely heavily on listening to the test runner and what it tells us. It usually tells them exactly what to do next. In this case, it's telling us to create a test. So, let's do that.

Where should you place your tests?

If you do try out the create-react-app template, you’ll notice that it contains a single unit test file, App.test.js , which exists in the same directory as the source file, App.js .

I don't recommend mixing production code with test code. For a start, it isn’t the conventional unit-testing approach, which uses two separate directories for production code and test code. More importantly, however, it’s likely that you won’t have a one-to-one mapping between production and test files.
主站蜘蛛池模板: 湖南省| 即墨市| 大荔县| 玛曲县| 金坛市| 南岸区| 略阳县| 奎屯市| 万全县| 济宁市| 唐河县| 册亨县| 堆龙德庆县| 伊宁市| 禄丰县| 武汉市| 利辛县| 漳州市| 成武县| 泗洪县| 赤峰市| 河曲县| 莫力| 叶城县| 安宁市| 合山市| 宿州市| 闵行区| 永靖县| 宜良县| 福鼎市| 长宁区| 黑水县| 四子王旗| 开江县| 大安市| 芦山县| 墨玉县| 夏邑县| 白银市| 常熟市|