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

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.
主站蜘蛛池模板: 阿图什市| 旌德县| 威信县| 克东县| 平湖市| 大同县| 阿克苏市| 醴陵市| 屏边| 旬阳县| 浙江省| 延长县| 洛浦县| 乌鲁木齐市| 五常市| 新余市| 漳州市| 靖江市| 新和县| 泸溪县| 平泉县| 武穴市| 乌兰浩特市| 锡林浩特市| 柳河县| 乐至县| 海盐县| 大余县| 祁连县| 中卫市| 金寨县| 西峡县| 三河市| 丽水市| 宜君县| 板桥市| 古田县| 平泉县| 仁怀市| 正蓝旗| 都兰县|