oldoc63 / learningFS

Web development back and front
0 stars 0 forks source link

Hooks #1063

Open oldoc63 opened 2 years ago

oldoc63 commented 2 years ago

We learned about the four main phases of a test: setup, execute, verify and teardown. In the last exercise, you may have notice that the setup and teardown steps were identical between tests. While execution and verification are unique to each test, setup and teardown are often similar or even identical for multiple tests within a test suite. The Mocha test framework provides functions that enable us to reduce repetition, simplify the scope of each test, and more finely control the execution of our test. These functions (also referred as hooks) are:

Each hook accepts a callback to be executed at various times during a test. The before ... hooks naturally happen before tests and are useful for separating out the setup steps of your tests. Meanwhile, the after ... hooks are executed after tests and are useful for separating out the teardown steps of your test.

oldoc63 commented 2 years ago

In this example, while each it() block could have set the test value to 5, using the beforeEach() hook allows us to avoid that repetition while keeping each test isolated. Keep in mind that not all setup and teardown steps should be included in these hooks. Occasionally, you may find that you need to perform some unique setup or teardown for a single test that you don't want to include in other tests.

oldoc63 commented 2 years ago
  1. path = './message.txt' is repeated in both tests, but only need to be assigned once. Inside the describe() block and above the first it() test, create the appropriate hook to simplify this. For now, use an empty callback function with your hook.
  2. Now, copy path = './message.txt' into the callback for your new hook and delete it from the it() blocks.
  3. We’ve moved a repetitive setup step out of the tests and into the before() hook. Run the test suite to make sure that the tests still pass.
oldoc63 commented 2 years ago
  1. fs.unlinkSync(path); is repeated at the end of both tests. Use the appropriate hook to have this teardown executed after each test. First, inside the describe() block and before the first it() test, create the appropriate hook to simplify this. For now, use an empty function.
  2. Now, copy fs.unlinkSync(path); into the callback for your new hook and delete it from the it() blocks.
  3. Confirm everything works by running the test suite!