headers 模块单元测试

之前我们测试了 headers 的基础方法模块,接下来我们会从业务角度测试 headers 的相关业务逻辑。

测试代码编写

test/headers.spec.ts

  1. import axios from '../src/index'
  2. import { getAjaxRequest } from './helper'
  3. function testHeaderValue(headers: any, key: string, val?: string): void {
  4. let found = false
  5. for (let k in headers) {
  6. if (k.toLowerCase() === key.toLowerCase()) {
  7. found = true
  8. expect(headers[k]).toBe(val)
  9. break
  10. }
  11. }
  12. if (!found) {
  13. if (typeof val === 'undefined') {
  14. expect(headers.hasOwnProperty(key)).toBeFalsy()
  15. } else {
  16. throw new Error(key + ' was not found in headers')
  17. }
  18. }
  19. }
  20. describe('headers', () => {
  21. beforeEach(() => {
  22. jasmine.Ajax.install()
  23. })
  24. afterEach(() => {
  25. jasmine.Ajax.uninstall()
  26. })
  27. test('should use default common headers', () => {
  28. const headers = axios.defaults.headers.common
  29. axios('/foo')
  30. return getAjaxRequest().then(request => {
  31. for (let key in headers) {
  32. if (headers.hasOwnProperty(key)) {
  33. expect(request.requestHeaders[key]).toEqual(headers[key])
  34. }
  35. }
  36. })
  37. })
  38. test('should add extra headers for post', () => {
  39. axios.post('/foo', 'fizz=buzz')
  40. return getAjaxRequest().then(request => {
  41. testHeaderValue(request.requestHeaders, 'Content-Type', 'application/x-www-form-urlencoded')
  42. })
  43. })
  44. test('should use application/json when posting an object', () => {
  45. axios.post('/foo/bar', {
  46. firstName: 'foo',
  47. lastName: 'bar'
  48. })
  49. return getAjaxRequest().then(request => {
  50. testHeaderValue(request.requestHeaders, 'Content-Type', 'application/json;charset=utf-8')
  51. })
  52. })
  53. test('should remove content-type if data is empty', () => {
  54. axios.post('/foo')
  55. return getAjaxRequest().then(request => {
  56. testHeaderValue(request.requestHeaders, 'Content-Type', undefined)
  57. })
  58. })
  59. it('should preserve content-type if data is false', () => {
  60. axios.post('/foo', false)
  61. return getAjaxRequest().then(request => {
  62. testHeaderValue(request.requestHeaders, 'Content-Type', 'application/x-www-form-urlencoded')
  63. })
  64. })
  65. test('should remove content-type if data is FormData', () => {
  66. const data = new FormData()
  67. data.append('foo', 'bar')
  68. axios.post('/foo', data)
  69. return getAjaxRequest().then(request => {
  70. testHeaderValue(request.requestHeaders, 'Content-Type', undefined)
  71. })
  72. })
  73. })

内部定义了 testHeaderValue 辅助函数,用于测试 headers 是否存在某个 header name 下的某个值。

至此我们完成了 ts-axiosheaders 模块相关业务逻辑的测试,下一节课我们会对 Axios 的实例做测试。