Skip to content

Add tests for React Native plugin #531

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

Merged
merged 1 commit into from
Mar 16, 2016
Merged
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
129 changes: 74 additions & 55 deletions plugins/react-native.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,80 +10,99 @@
'use strict';

var DEVICE_PATH_RE = /^\/var\/mobile\/Containers\/Bundle\/Application\/[^\/]+\/[^\.]+\.app/;

/**
* Strip device-specific IDs from React Native file:// paths
*/
function normalizeUrl(url) {
return url
.replace(/^file\:\/\//, '')
.replace(DEVICE_PATH_RE, '');
}

function reactNativePlugin(Raven) {
function urlencode(obj) {
var pairs = [];
for (var key in obj) {
if ({}.hasOwnProperty.call(obj, key))
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
return pairs.join('&');
}

function xhrTransport(options) {
var request = new XMLHttpRequest();
request.onreadystatechange = function (e) {
if (request.readyState !== 4) {
return;
}

if (request.status === 200) {
if (options.onSuccess) {
options.onSuccess();
}
} else {
if (options.onError) {
options.onError();
}
}
};

request.open('POST', options.url + '?' + urlencode(options.auth));

// NOTE: React Native ignores CORS and will NOT send a preflight
// request for application/json.
// See: https://facebook.github.io/react-native/docs/network.html#xmlhttprequest
request.setRequestHeader('Content-type', 'application/json');

// Sentry expects an Origin header when using HTTP POST w/ public DSN.
// Just set a phony Origin value; only matters if Sentry Project is configured
// to whitelist specific origins.
request.setRequestHeader('Origin', 'react-native://');
request.send(JSON.stringify(options.data));
/**
* Extract key/value pairs from an object and encode them for
* use in a query string
*/
function urlencode(obj) {
var pairs = [];
for (var key in obj) {
if ({}.hasOwnProperty.call(obj, key))
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
return pairs.join('&');
}

/**
* Initializes React Native plugin
*/
function reactNativePlugin(Raven) {
// react-native doesn't have a document, so can't use default Image
// transport - use XMLHttpRequest instead
Raven.setTransport(xhrTransport);

Raven.setTransport(reactNativePlugin._transport);

// Use data callback to strip device-specific paths from stack traces
Raven.setDataCallback(function (data) {
if (data.culprit) {
data.culprit = normalizeUrl(data.culprit);
}

if (data.exception) {
// if data.exception exists, all of the other keys are guaranteed to exist
data.exception.values[0].stacktrace.frames.forEach(function (frame) {
frame.filename = normalizeUrl(frame.filename);
});
}
});
Raven.setDataCallback(reactNativePlugin._normalizeData);

var defaultHandler = ErrorUtils.getGlobalHandler && ErrorUtils.getGlobalHandler() || ErrorUtils._globalHandler;

ErrorUtils.setGlobalHandler(function(){
ErrorUtils.setGlobalHandler(function() {
var error = arguments[0];
defaultHandler.apply(this, arguments)
Raven.captureException(error);
});
}

/**
* Custom HTTP transport for use with React Native applications.
*/
reactNativePlugin._transport = function (options) {
var request = new XMLHttpRequest();
request.onreadystatechange = function (e) {
if (request.readyState !== 4) {
return;
}

if (request.status === 200) {
if (options.onSuccess) {
options.onSuccess();
}
} else {
if (options.onError) {
options.onError();
}
}
};

request.open('POST', options.url + '?' + urlencode(options.auth));

// NOTE: React Native ignores CORS and will NOT send a preflight
// request for application/json.
// See: https://facebook.github.io/react-native/docs/network.html#xmlhttprequest
request.setRequestHeader('Content-type', 'application/json');

// Sentry expects an Origin header when using HTTP POST w/ public DSN.
// Just set a phony Origin value; only matters if Sentry Project is configured
// to whitelist specific origins.
request.setRequestHeader('Origin', 'react-native://');
request.send(JSON.stringify(options.data));
};

/**
* Strip device-specific IDs found in culprit and frame filenames
* when running React Native applications on a physical device.
*/
reactNativePlugin._normalizeData = function (data) {
if (data.culprit) {
data.culprit = normalizeUrl(data.culprit);
}

if (data.exception) {
// if data.exception exists, all of the other keys are guaranteed to exist
data.exception.values[0].stacktrace.frames.forEach(function (frame) {
frame.filename = normalizeUrl(frame.filename);
});
}
};

module.exports = reactNativePlugin;
150 changes: 150 additions & 0 deletions test/plugins/react-native.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
var _Raven = require('../../src/raven');
var reactNativePlugin = require('../../plugins/react-native');

window.ErrorUtils = {};

var Raven;
describe('React Native plugin', function () {
beforeEach(function () {
Raven = new _Raven();
Raven.config('http://[email protected]:80/2');
});

describe('_normalizeData()', function () {
it('should normalize culprit and frame filenames/URLs', function () {
var data = {
project: '2',
logger: 'javascript',
platform: 'javascript',

culprit: 'file:///var/mobile/Containers/Bundle/Application/ABC/123.app/app.js',
message: 'Error: crap',
exception: {
type: 'Error',
values: [{
stacktrace: {
frames: [{
filename: 'file:///var/mobile/Containers/Bundle/Application/ABC/123.app/file1.js',
lineno: 10,
colno: 11,
'function': 'broken'

}, {
filename: 'file:///var/mobile/Containers/Bundle/Application/ABC/123.app/file2.js',
lineno: 12,
colno: 13,
'function': 'lol'
}]
}
}],
}
};
reactNativePlugin._normalizeData(data);

assert.equal(data.culprit, '/app.js');
var frames = data.exception.values[0].stacktrace.frames;
assert.equal(frames[0].filename, '/file1.js');
assert.equal(frames[1].filename, '/file2.js');
});
});

describe('_transport()', function () {
beforeEach(function () {
this.xhr = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];

this.xhr.onCreate = function (xhr) {
requests.push(xhr);
};
});

afterEach(function () {
this.xhr.restore();
});

it('should open and send a new XHR POST with urlencoded auth, fake origin', function () {
reactNativePlugin._transport({
url: 'https://example.org/1',
auth: {
sentry_version: '7',
sentry_client: 'raven-js/2.2.0',
sentry_key: 'abc123'
},
data: {foo: 'bar'}
});

var lastXhr = this.requests.shift();
lastXhr.respond(200);

assert.equal(
lastXhr.url,
'https://example.org/1?sentry_version=7&sentry_client=raven-js%2F2.2.0&sentry_key=abc123'
);
assert.equal(lastXhr.method, 'POST');
assert.equal(lastXhr.requestBody, '{"foo":"bar"}');
assert.equal(lastXhr.requestHeaders['Content-type'], 'application/json');
assert.equal(lastXhr.requestHeaders['Origin'], 'react-native://');
});

it('should call onError callback on failure', function () {
var onError = this.sinon.stub();
var onSuccess = this.sinon.stub();
reactNativePlugin._transport({
url: 'https://example.org/1',
auth: {},
data: {foo: 'bar'},
onError: onError,
onSuccess: onSuccess
});

var lastXhr = this.requests.shift();
lastXhr.respond(401);

assert.isTrue(onError.calledOnce);
assert.isFalse(onSuccess.calledOnce);
});

it('should call onSuccess callback on success', function () {
var onError = this.sinon.stub();
var onSuccess = this.sinon.stub();
reactNativePlugin._transport({
url: 'https://example.org/1',
auth: {},
data: {foo: 'bar'},
onError: onError,
onSuccess: onSuccess
});

var lastXhr = this.requests.shift();
lastXhr.respond(200);

assert.isTrue(onSuccess.calledOnce);
assert.isFalse(onError.calledOnce);
});
});

describe('ErrorUtils global error handler', function () {
beforeEach(function () {
var self = this;
ErrorUtils.setGlobalHandler = function(fn) {
self.globalErrorHandler = fn;
};
self.defaultErrorHandler = self.sinon.stub();
ErrorUtils.getGlobalHandler = function () {
return self.defaultErrorHandler;
}
});

it('should call the default React Native handler and Raven.captureException', function () {
reactNativePlugin(Raven);
var err = new Error();
this.sinon.stub(Raven, 'captureException');

this.globalErrorHandler(err);

assert.isTrue(this.defaultErrorHandler.calledOnce);
assert.isTrue(Raven.captureException.calledOnce);
assert.equal(Raven.captureException.getCall(0).args[0], err);
});
});
});