Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用xhr模拟测试AJAX函数失败_Javascript_Jestjs - Fatal编程技术网

Javascript 使用xhr模拟测试AJAX函数失败

Javascript 使用xhr模拟测试AJAX函数失败,javascript,jestjs,Javascript,Jestjs,我正在尝试从我的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()

我正在尝试从我的
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

  {}

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

解决方案

将尾部的
/
添加到您提供的url
xhrMock.post()

错误详细信息

url是
http://localhost

这会变成的
req.url()

{
  protocol: 'http',
  host: 'localhost',
  path: '/',
  query: {}
}
对该对象调用
toString()
,将返回
'http://localhost/“

xhr mock
通过执行
req.url().toString()==url


'http://localhost/' === 'http://localhost“
返回
false
因此
xhr mock
返回了一个错误,没有处理程序返回响应。

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

用法非常简单:

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;