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
{}
这主要是基于文档,我不明白为什么它会失败解决方案 将尾部的
/
添加到您提供的urlxhrMock.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;