jest笔记

支持的Matchers

  • toBe&& toEqual
  • 真值,结果同if(/*statement*/)
  • 数值,toBeGreaterThan, toBeGreaterThanOrEqual, toBeLessThan, toBeLessThanOrEqual, toBe, toEqual
  • String,toMatch
  • 数组和Iterables,toContain
  • 异常,toThrow

异步测试

  • 回调,done
  • Promisethen里直接expectcatch需要加一条语句expect.assertions(1);
  • .resolves/.rejects
  • Async/Await,类似于Promise

describe

jest会先调用describe,因此一些有意义的逻辑应该放在beforeEachafterEach里。
jest会按照test定义的顺序来执行test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
describe('1', () => {
console.log('1-describe');
beforeAll(() => console.log('1-once-before'));
afterAll(() => console.log('1-once-after'));
beforeEach(() => console.log('1-each-before'));
afterEach(() => console.log('1-each-after'));

test('1', () => {
console.log('1-test');
expect(1).toBe(1);
})

describe('2', () => {
console.log('2-describe');
beforeAll(() => console.log('2-once-before'));
afterAll(() => console.log('2-once-after'));
beforeEach(() => console.log('2-each-before'));
afterEach(() => console.log('2-each-after'));

test('2', () => {
console.log('2-test');
expect(2).toBe(2);
})
});
})

// 1-describe
// 2-describe
// 1-once-before
// 1-each-before
// 1-test
// 1-each-after
// 2-once-before
// 1-each-before
// 2-each-before
// 2-test
// 2-each-after
// 1-each-after
// 2-once-after
// 1-once-after

调试技巧

当某个test出错时,可以使用test.only来检查是它本身的错误,还是与其他test有关。

如果test.only时通过,和其他test一起就不通过,猜测很可能与共享状态有关。可以在beforeEach里重置共享状态来验证。

1
2
3
4
5
6
7
test.only(() => {
expect(1).toBe(1);
})

test(() => {
expect('aaa').toMatch(/a/);
})