Testing An Ajax Function With Xhr-mock Fails
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
Solution 1:
Solution
add a trailing /
to the url you are giving xhrMock.post()
Error Details
The url is http://localhost
.
That turns into a req.url()
of
{
protocol: 'http',
host: 'localhost',
path: '/',
query: {}
}
Calling toString()
on that object returns 'http://localhost/'
xhr-mock
compares the URLs by doing req.url().toString() === url
'http://localhost/' === 'http://localhost'
returns false
so xhr-mock
is returning an error that no handler returned a response.
Solution 2:
I found I had some problems as well and using the following module was a better alternative for me:
https://github.com/berniegp/mock-xmlhttprequest
Usage is pretty straight forward:
constMockXMLHttpRequest = require('mock-xmlhttprequest');
constMockXhr = MockXMLHttpRequest.newMockXhr();
// Mock JSON responseMockXhr.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 mockglobal.XMLHttpRequest = MockXhr;
Post a Comment for "Testing An Ajax Function With Xhr-mock Fails"