🌖 headers 模块单元测试
# 测试代码编写
创建文件 test/headers.spec.ts
:
function testHeaderValue(headers: any, key: string, val?: string): void {
let found = false
for (let k in headers) {
if (k.toLowerCase() === key.toLowerCase()) {
found = true
expect(headers[k]).toBe(val)
break
}
}
if (!found) {
if (typeof val === 'undefined') {
expect(headers.hasOwnProperty(key)).toBeFalsy()
} else {
throw new Error(key + ' was not found in headers')
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
定义这个辅助函数,用于测试
headers
是否存在某个header
下的某个值。
import axios from '../src'
import { getAjaxRequest } from './helper'
describe('headers', () => {
beforeEach(() => {
jasmine.Ajax.install()
})
afterEach(() => {
jasmine.Ajax.uninstall()
})
test('should use default common headers', () => {
const headers = axios.defaults.headers.common
axios('/foo')
return getAjaxRequest().then(request => {
for (let key in headers) {
if (headers.hasOwnProperty(key)) {
expect(request.requestHeaders[key]).toEqual(headers[key])
}
}
})
})
test('should add extra headers for post', () => {
axios.post('/foo', 'fizz=buzz')
return getAjaxRequest().then(request => {
testHeaderValue(request.requestHeaders, 'Content-Type', 'application/x-www-form-urlencoded')
})
})
test('should use application/json when posting an object', () => {
axios.post('/foo', {
firstName: 'foo',
lastName: 'bar'
})
return getAjaxRequest().then(request => {
testHeaderValue(request.requestHeaders, 'Content-Type', 'application/json;charset=utf-8')
})
})
test('should remove content-type if data is empty', () => {
axios.post('/foo')
return getAjaxRequest().then(request => {
testHeaderValue(request.requestHeaders, 'Content-Type', undefined)
})
})
it('should preserve content-type if data is false', () => {
axios.post('/foo', false)
return getAjaxRequest().then(request => {
testHeaderValue(request.requestHeaders, 'Content-Type', 'application/x-www-form-urlencoded')
})
})
test('should remove content-type if data is FormData', () => {
const data = new FormData()
data.append('foo', 'bar')
axios.post('/foo', data)
return getAjaxRequest().then(request => {
testHeaderValue(request.requestHeaders, 'Content-Type', undefined)
})
})
})
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
编辑 (opens new window)
📢 上次更新: 2022/09/02, 10:18:16