你将如何测试使用Promise完成的Jasmine和Vanilla JS Ajax调用?

时间:2016-11-04 13:09:20

标签: javascript ajax jasmine promise

我来自这里:How to make an AJAX call without jQuery?

很难模仿Promise,AJAX调用或两者兼而有之。

到目前为止,我已尝试使用jasmine-ajax,但它似乎有一个bug ...而且显然"仅适用于浏览器环境"。

我还试图模拟XMLHttpRequest对象,但没有成功。

所以,我不确定我的选择是什么:

function get(url) {
  return new Promise((resolve, reject) => {
    const req = new XMLHttpRequest();
    req.open('GET', url);
    req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
    req.onerror = (e) => reject(Error(`Network Error: ${e}`));
    req.send();
  });
}

1 个答案:

答案 0 :(得分:0)

概念验证如何模拟 XMLHttpRequest

function get(url) {
  return new Promise((resolve, reject) => {
    const req = new XMLHttpRequest();
    req.open('GET', url);
    req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
    req.onerror = (e) => reject(Error(`Network Error: ${e}`));
    req.send();
  });
}

describe('XMLHttpRequest', function() {
  var xhr
  var urls

  beforeEach(() => {
    xhr = {
      open: (_type_, _url_) => {
        xhr.status = urls[_url_].status
        xhr.response = urls[_url_].response
        xhr.statusText = urls[_url_].statusText
      },
      send: () => {
        setTimeout(xhr.onload, 1)
      }
    }

    XMLHttpRequest = jasmine.createSpy(xhr).and.returnValue(xhr)
  })

  it('resolves query with `response`', function(done) {
    urls = {
      'http://foo/bar': {
        response: 'some other value',
        status: 200
      }
    };

    get('http://foo/bar')
    .then(r => expect(r).toBe('some other value'), e => expect(e).toBe(undefined))
      .then(done)
  })

  it('rejects query with `statusText`', function(done) {
    urls = {
      'http://baz/quux': {
        response: 'some other value',
        status: 500,
        statusText: 'some error'
      }
    };

    get('http://baz/quux')
    .then(r => expect(r).toBe(undefined), e => expect(e.message).toBe('some error'))
      .then(done)
  })
})
<script src="https://safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<link href="https://safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />