test.js 2.2 KB
Newer Older
D
David Graham 已提交
1 2 3 4 5 6
MockXHR.responses = {
  '/hello': function(xhr) {
    xhr.respond(200, 'hi')
  },
  '/boom': function(xhr) {
    xhr.respond(500, 'boom')
D
David Graham 已提交
7 8 9 10 11 12
  },
  '/json': function(xhr) {
    xhr.respond(200, JSON.stringify({name: 'Hubot', login: 'hubot'}))
  },
  '/json-error': function(xhr) {
    xhr.respond(200, 'not json {')
D
David Graham 已提交
13 14 15 16 17
  }
}

window.XMLHttpRequest = MockXHR

D
David Graham 已提交
18
asyncTest('populates response body', 3, function() {
D
David Graham 已提交
19
  fetch('/hello').then(function(response) {
D
David Graham 已提交
20
    equal(MockXHR.last().method, 'GET')
D
David Graham 已提交
21 22 23 24 25
    equal(response.status, 200)
    equal(response.body, 'hi')
    start()
  })
})
D
David Graham 已提交
26

D
David Graham 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40
asyncTest('sends headers', 2, function() {
  fetch('/hello', {
    headers: {
      'Accept': 'application/json',
      'X-Test': '42'
    }
  }).then(function(response) {
    var request = MockXHR.last()
    equal(request.headers['Accept'], 'application/json')
    equal(request.headers['X-Test'], '42')
    start()
  })
})

D
David Graham 已提交
41 42 43 44 45 46 47 48 49
asyncTest('resolves text promise', 1, function() {
  fetch('/hello').then(function(response) {
    return response.text()
  }).then(function(text) {
    equal(text, 'hi')
    start()
  })
})

D
David Graham 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
asyncTest('parses json response', 2, function() {
  fetch('/json').then(function(response) {
    return response.json()
  }).then(function(json) {
    equal(json.name, 'Hubot')
    equal(json.login, 'hubot')
    start()
  })
})

asyncTest('handles json parse error', 2, function() {
  fetch('/json-error').then(function(response) {
    return response.json()
  }).catch(function(error) {
    ok(error instanceof Error, 'JSON exception is an Error instance')
    ok(error.message, 'JSON exception has an error message')
    start()
  })
})
D
David Graham 已提交
69 70 71 72 73 74 75 76 77 78

asyncTest('resolves blob promise', 2, function() {
  fetch('/hello').then(function(response) {
    return response.blob()
  }).then(function(blob) {
    ok(blob instanceof Blob, 'blob is a Blob instance')
    equal(blob.size, 2)
    start()
  })
})
D
David Graham 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

asyncTest('sends encoded post body', 2, function() {
  fetch('/hello', {
    method: 'post',
    body: {
      name: 'Hubot',
      title: 'Hubot Robawt',
      undef: undefined,
      nil: null
    }
  }).then(function(response) {
    var request = MockXHR.last()
    equal(request.method, 'post')
    equal(request.data, 'name=Hubot&title=Hubot+Robawt&nil=')
    start()
  })
})