Skip to content

Commit

Permalink
Throw error if non-cordova module is required
Browse files Browse the repository at this point in the history
Resolves apache#689
  • Loading branch information
raphinesse committed Sep 28, 2018
1 parent 81439dc commit c801811
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 21 deletions.
32 changes: 13 additions & 19 deletions spec/hooks/Context.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/

const rewire = require('rewire');
const events = require('cordova-common').events;
const { CordovaError } = require('cordova-common');

describe('hooks/Context', () => {
let Context;
Expand All @@ -28,16 +28,10 @@ describe('hooks/Context', () => {
});

describe('requireCordovaModule', () => {
let warnSpy, requireCordovaModule;
let requireCordovaModule;

beforeEach(() => {
requireCordovaModule = Context.prototype.requireCordovaModule;
warnSpy = jasmine.createSpy('warnSpy');
events.on('warn', warnSpy);
});

afterEach(() => {
events.removeListener('warn', warnSpy);
});

it('correctly resolves cordova-* dependencies', () => {
Expand Down Expand Up @@ -90,17 +84,17 @@ describe('hooks/Context', () => {
expect(requireSpy).toHaveBeenCalledWith('cordova-libre');
});

it('emits a warning if non-cordova module is requested', () => {
requireCordovaModule('q');

expect(requireSpy).toHaveBeenCalledWith('q');
expect(warnSpy).toHaveBeenCalledTimes(1);

const message = warnSpy.calls.argsFor(0)[0];
expect(message).toContain('requireCordovaModule');
expect(message).toContain('non-cordova module');
expect(message).toContain('deprecated');
expect(message).toContain('"q"');
it('throws if non-cordova module is requested', () => {
const expectErrorOnRequire = m =>
expect(() => requireCordovaModule(m))
.toThrowError(CordovaError, /non-cordova module/);

expectErrorOnRequire('q');
expectErrorOnRequire('.');
expectErrorOnRequire('..');
expectErrorOnRequire('./asd');
expectErrorOnRequire('../qwe');
expectErrorOnRequire('/foo');
});
});

Expand Down
5 changes: 3 additions & 2 deletions src/hooks/Context.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

var path = require('path');
var events = require('cordova-common').events;
var CordovaError = require('cordova-common').CordovaError;

/**
* Creates hook script context
Expand Down Expand Up @@ -61,9 +62,9 @@ Context.prototype.requireCordovaModule = function (modulePath) {
const [pkg, ...pkgPath] = modulePath.split('/');

if (!pkg.match(/^cordova-[^/]+/)) {
events.emit('warn',
throw new CordovaError(
`Using "requireCordovaModule" to load non-cordova module ` +
`"${modulePath}" is deprecated. Instead, add this module to ` +
`"${modulePath}" is not supported. Instead, add this module to ` +
`your dependencies and use regular "require" to load it.`
);
}
Expand Down

0 comments on commit c801811

Please sign in to comment.