- Objective:
- Breadcrumb:
# 概念阐释
## 语义
在测试代码中,通常设置和[[js testing mocha 测试 拆卸隔离 Teardown]]环节会高度重复,Hooks(钩子)可以使代码更加简洁。
## 语法
- `beforeEach(()=>{});` 在每个测试之前运行回调
- `afterEach(()=>{});` 在每个测试之后运行回调,通常拆卸需要在每个测试之后都回调
- `before(()=>{});`在第一个测试之前运行回调,通常用于永远不会发生改变的变量;
- `after(()=>{});` 在最后一个测试之后运行回调
# 实例

# 相关内容
# 问题
1. 将代码中重复部分改为hooks
```js
const assert = require('assert');
const fs = require('fs');
let path, str;
describe('appendFileSync', () => {
// Write hooks above the tests
it('writes a string to text file at given path name', () => {
// Setup
path = './message.txt';
str = 'Hello Node.js';
// Exercise: write to file
fs.appendFileSync(path, str);
// Verify: compare file contents to string
const contents = fs.readFileSync(path);
assert.equal(contents.toString(), str);
// Teardown: restore file
fs.unlinkSync(path);
});
it('writes an empty string to text file at given path name', () => {
// Setup
path = './message.txt';
str = '';
// Exercise: write to file
fs.appendFileSync(path, str);
// Verify: compare file contents to string
const contents = fs.readFileSync(path);
assert.equal(contents.toString(), str);
// Teardown: restore file
fs.unlinkSync(path);
});
});
```
# 问题答案
```js
const assert = require('assert');
const fs = require('fs');
let path, str;
describe('appendFileSync', () => {
// Write hooks above the tests
before( ()=>{
path = './message.txt';
});
afterEach(()=>{
fs.unlinkSync(path);
});
it('writes a string to text file at given path name', () => {
// Setup
str = 'Hello Node.js';
// Exercise: write to file
fs.appendFileSync(path, str);
// Verify: compare file contents to string
const contents = fs.readFileSync(path);
assert.equal(contents.toString(), str);
// Teardown: restore file
});
it('writes an empty string to text file at given path name', () => {
// Setup
str = '';
// Exercise: write to file
fs.appendFileSync(path, str);
// Verify: compare file contents to string
const contents = fs.readFileSync(path);
assert.equal(contents.toString(), str);
// Teardown: restore file
});
});
```
# 参考资料
- [Hooks](https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-front-end-development/tracks/fscj-22-javascript-testing/modules/wdcp-22-write-good-tests-with-mocha-764e85ca-0abf-4da9-91a2-43f8d593eab8/lessons/automate-organize-tests/exercises/hooks)