When trying to use the example code from http://sinonjs.org/docs/#server, I get the following error: TypeError: Attempted to wrap undefined property undefined as function.
Here's the function I'm trying to test:
function xhrPost(url, options) {
let xhr = new XMLHttpRequest();
let {data, success, fail} = options;
if (!url || !isString(url)) {
throw new TypeError('URL string must be provided for an xhr call');
}
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if (success) {
xhr.addEventListener('load', success);
}
if (fail) {
xhr.addEventListener('error', fail);
}
if (data) {
data = serializeRequestData(data);
}
xhr.send(data || null);
}
The unit test code is:
QUnit.module('utils', {
beforeEach() {
// copy/pasteed from example in docs
let requests = this.requests = [];
this.xhr = sinon.useFakeXMLHttpRequest();
this.xhr.onCreate = function (xhr) {
requests.push(xhr);
};
},
afterEach() {
// copy/pasteed from example in docs
this.xhr.restore();
}
});
QUnit.test('xhr helper function', function (assert) {
xhrPost('/api.php', {
data: {
title: 'foo'
},
success: sinon.spy,
fail: sinon.spy
});
// copy/pasted from example in docs
this.requests[0].respond(200, { "Content-Type": "application/json" },
'[{ "id": 12, "comment": "Hey there" }]');
assert(callback.calledWith([{ id: 12, comment: "Hey there" }]));
});
The fake request goes through without issues, but when I call respond(), I get the above error. If I comment out the success and fail functions of xhrPost, I don't get an error. The problem seems to stem from a combination of calling respond with onerror or onfail events (and I did tried switching to onerror and onfail instead of addEventListener but no dice).
This seems to me like a bug in the code, but please let me know if I'm doing something wrong. Thanks!
And, I answered my own question. Should be invoking sinon.spy, like:
```es6
xhrPost('/api.php', {
data: {
title: 'foo'
},
success: sinon.spy(),
fail: sinon.spy()
});
Closing the issue!
``````
Most helpful comment
And, I answered my own question. Should be invoking
sinon.spy, like:```
es6 xhrPost('/api.php', { data: { title: 'foo' }, success: sinon.spy(), fail: sinon.spy() });Closing the issue!
``````