api.test.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*global fetch*/
  2. "use strict";
  3. require('es6-promise').polyfill();
  4. require('../fetch-npm-node');
  5. var expect = require('chai').expect;
  6. var nock = require('nock');
  7. var good = 'hello world. 你好世界。';
  8. var bad = 'good bye cruel world. 再见残酷的世界。';
  9. function responseToText(response) {
  10. if (response.status >= 400) throw new Error("Bad server response");
  11. return response.text();
  12. }
  13. describe('fetch', function() {
  14. before(function() {
  15. nock('https://mattandre.ws')
  16. .get('/succeed.txt')
  17. .reply(200, good);
  18. nock('https://mattandre.ws')
  19. .get('/fail.txt')
  20. .reply(404, bad);
  21. });
  22. it('should be defined', function() {
  23. expect(fetch).to.be.a('function');
  24. });
  25. it('should facilitate the making of requests', function(done) {
  26. fetch('//mattandre.ws/succeed.txt')
  27. .then(responseToText)
  28. .then(function(data) {
  29. expect(data).to.equal(good);
  30. done();
  31. })
  32. .catch(done);
  33. });
  34. it('should do the right thing with bad requests', function(done) {
  35. fetch('//mattandre.ws/fail.txt')
  36. .then(responseToText)
  37. .catch(function(err) {
  38. expect(err.toString()).to.equal("Error: Bad server response");
  39. done();
  40. })
  41. .catch(done);
  42. });
  43. });