Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Making parse more robust #27

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/najax.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ function najax (uri, options, callback) {
if (o.dataType === 'json' || o.dataType === 'jsonp') {
// replace control characters
try {
data = JSON.parse(data.replace(/[\cA-\cZ]/gi, ''))
data = _.attempt(JSON.parse.bind(null, data.replace(/[\cA-\cZ]/gi, '')))
} catch (e) {
return errorHandler(e)
}
Expand All @@ -173,6 +173,7 @@ function najax (uri, options, callback) {
jqXHR.statusText = statusText

if (_.isFunction(o.success)) o.success(data, statusText, jqXHR)
if (_.isFunction(o.complete)) o.complete(jqXHR)
// success, statusText, jqXHR
dfd.resolve(data, statusText, jqXHR)
} else {
Expand Down
29 changes: 29 additions & 0 deletions test/test-najax.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,19 @@ describe('url', function (next) {
najax({ url: 'http://www.example.com' }, createSuccess(done))
})

it('should not fail when result is broken JSON', function (done) {
mockPlain('get')
najax({url: 'http://www.example.com', dataType: 'json'}, jsonError(done))
})

it('should succeed when result is good JSON', function (done) {
nock('http://www.example.com')
.get('/')
.reply(200, {'test': 'ok'})

najax({url: 'http://www.example.com', dataType: 'json'}, jsonSuccess(done))
})

it('should parse auth from the url', function (done) {
mockAuth('get')
najax({ url: 'http://' + authString + '@www.example.com' }, createSuccess(done))
Expand Down Expand Up @@ -295,6 +308,22 @@ function createSuccess (done) {
}
}

function jsonSuccess (done) {
return function (data, statusText) {
expect(data.test).to.equal('ok')
expect(statusText).to.equal('success')
done()
}
}

function jsonError (done) {
return function (data, statusText) {
expect(data.test).to.be.undefined
expect(statusText).to.equal('success')
done()
}
}

function error (e) {
throw e
}