Jest学习文档(三)

106 阅读2分钟

Jest代码复用

在编写测试代码的过程中, 对于部分测试片段, 我们会有一些相同的处理逻辑, 这时候, 我们希望可以把它们提取出来并复用, jest官方为我们提供了一些hooks以便我们复用我们的代码

beforeEach

beforeEach接收一个回调函数, 在每个test被调用之前都会调用beforeEach的回调函数, 我通常用来为一些公共的变量设置值. 需要注意的是, 我们不能在回调函数里直接定义公共变量, 因为它和test的回调处于两个独立的作用域中

afterEach

和beforeEach一样, 也接受一个回调函数, 在每个test被调用之后都会调用afterEach的回调函数, 我们可以用来清空某些状态, 但是我没怎么用到, 因为beforeEach已经满足了我大部分的需求.

beforeAll

接收一个回调函数, 并在在第一个test回调被调用之前执行. 与beforeEach不同的是, 在整个测试文件中, 只会调用一次, 且优先级更高

afterAll

和beforeAll同理

describe

可以用来定义测试组, 在它的回调函数里, 可以使用只针对于该测试组before/after的hooks

describe('matching cities to foods', () => {
  // Applies only to tests in this describe block
  beforeEach(() => {
    return initializeFoodDatabase();
  });

  test('Vienna <3 veal', () => {
    expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
  });

  test('San Juan <3 plantains', () => {
    expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
  });
});

执行顺序

最后, 唯一值得强调的就是当有多个hooks时, 它们的执行顺序, 下面这段代码可以很好的表示

beforeEach(() => console.log('connection setup'));
beforeEach(() => console.log('database setup'));

afterEach(() => console.log('database teardown'));
afterEach(() => console.log('connection teardown'));

test('test 1', () => console.log('test 1'));

describe('extra', () => {
  beforeEach(() => console.log('extra database setup'));
  afterEach(() => console.log('extra database teardown'));
  console.log("describe run");
  test('test 2', () => console.log('test 2'));
});

// describe run
// connection setup
// database setup
// test 1
// database teardown
// connection teardown

// connection setup
// database setup
// extra database setup
// test 2
// extra database teardown
// database teardown
// connection teardown

值得注意的是, describe的回调会在所有回调之前执行