【问题标题】:Testing an AJAX function with xhr-mock fails使用 xhr-mock 测试 AJAX 函数失败
【发布时间】:2019-01-25 12:58:10
【问题描述】:

我正在尝试通过我的network.js 测试以下功能:

export function post (data) {
  return new Promise(function (resolve, reject) {
    // need to log to the root
    var url = window.location.protocol + '//' + window.location.hostname
    var xhr = new XMLHttpRequest()

    xhr.onreadystatechange = () => {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 204) {
          resolve(null)
        } else {
          reject(new Error('an error ocurred whilst sending the request'))
        }
      }
    }

    xhr.open('POST', url, true)
    xhr.setRequestHeader('Content-type', 'application/json')
    xhr.send(JSON.stringify(data))
  })
}

我的测试用例如下所示:

import xhrMock from 'xhr-mock'
import * as network from '../src/network'

describe('Payload networking test suite', function () {
  beforeEach(() => xhrMock.setup())

  afterEach(() => xhrMock.teardown())

  test('POSTs JSON string', async () => {
    expect.assertions(1)

    xhrMock.post(window.location.protocol + '//' + window.location.hostname, (req, res) => {
      expect(req.header('Content-Type')).toEqual('application/json')
      return res.status(204)
    })

    await network.post({})
  })
})

运行我的测试套件时,我得到:

xhr-mock: No handler returned a response for the request.

  POST http://localhost/ HTTP/1.1
  content-type: application/json

  {}

这主要基于文档,我不明白为什么它会失败

【问题讨论】:

    标签: javascript jestjs


    【解决方案1】:

    我发现我也遇到了一些问题,使用以下模块对我来说是一个更好的选择:

    https://github.com/berniegp/mock-xmlhttprequest

    用法非常简单:

    const MockXMLHttpRequest = require('mock-xmlhttprequest');
    const MockXhr = MockXMLHttpRequest.newMockXhr();
    
    // Mock JSON response
    MockXhr.onSend = (xhr) => {
      const responseHeaders = { 'Content-Type': 'application/json' };
      const response = '{ "message": "Success!" }';
      xhr.respond(200, responseHeaders, response);
    };
    
    // Install in the global context so "new XMLHttpRequest()" uses the XMLHttpRequest mock
    global.XMLHttpRequest = MockXhr;
    

    【讨论】:

      【解决方案2】:

      解决方案

      在您提供xhrMock.post() 的网址中添加尾随/

      错误详情

      网址是http://localhost

      这就变成了req.url()

      {
        protocol: 'http',
        host: 'localhost',
        path: '/',
        query: {}
      }
      

      对该对象调用toString()会返回'http://localhost/'

      xhr-mock compares the URLs 通过做req.url().toString() === url

      'http://localhost/' === 'http://localhost' 返回 false 所以 xhr-mock 返回一个没有处理程序返回响应的错误。

      【讨论】:

        猜你喜欢
        • 2018-08-02
        • 1970-01-01
        • 2017-03-09
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 2018-10-14
        • 1970-01-01
        相关资源
        最近更新 更多