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

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.
主站蜘蛛池模板: 南陵县| 新竹市| 泉州市| 安溪县| 河东区| 榆中县| 会泽县| 周口市| 永年县| 澄城县| 大新县| 时尚| 德庆县| 沛县| 青神县| 西丰县| 从化市| 霍山县| 纳雍县| 马鞍山市| 都江堰市| 黑山县| 嘉定区| 邵阳县| 景泰县| 鹰潭市| 恩平市| 榆社县| 青田县| 沈阳市| 民县| 获嘉县| 昌邑市| 全州县| 武陟县| 肇州县| 瑞金市| 阿拉善盟| 饶河县| 乌鲁木齐县| 额济纳旗|