使用xhr-mock测试AJAX功能失败 [英] Testing an AJAX function with xhr-mock fails

查看:349
本文介绍了使用xhr-mock测试AJAX功能失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的network.js中测试以下功能:

I'm trying to test the following function from my 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({})
  })
})

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

When running my test suite I'm getting:

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

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

  {}

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

This is mostly based on the documentation and I don't understand why its failing

推荐答案

解决方案

在您提供的xhrMock.post()

错误详细信息

网址是http://localhost.

变成

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

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

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

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

'http://localhost/' === 'http://localhost' returns false so xhr-mock is returning an error that no handler returned a response.

这篇关于使用xhr-mock测试AJAX功能失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆