Skip to content

Commit

Permalink
Merge pull request #1715 from sinonjs/sinon-es6-module-detection
Browse files Browse the repository at this point in the history
Throw meaningful error stubbing ECMAScript Module
  • Loading branch information
fatso83 committed Mar 5, 2018
2 parents b491a57 + 51cdafe commit d7fb7d5
Show file tree
Hide file tree
Showing 9 changed files with 373 additions and 1,187 deletions.
7 changes: 6 additions & 1 deletion lib/sinon/spy.js
Expand Up @@ -8,6 +8,7 @@ var functionToString = require("./util/core/function-to-string");
var getPropertyDescriptor = require("./util/core/get-property-descriptor");
var sinonMatch = require("./match");
var deepEqual = require("./util/core/deep-equal").use(sinonMatch);
var isEsModule = require("./util/core/is-es-module");
var spyCall = require("./call");
var wrapMethod = require("./util/core/wrap-method");
var sinonFormat = require("./util/core/format");
Expand All @@ -25,12 +26,16 @@ var callId = 0;
function spy(object, property, types) {
var descriptor, methodDesc;

if (isEsModule(object)) {
throw new TypeError("ES Modules cannot be spied");
}

if (!property && typeof object === "function") {
return spy.create(object);
}

if (!object && !property) {
return spy.create(function () { });
return spy.create(function () {});
}

if (!types) {
Expand Down
5 changes: 5 additions & 0 deletions lib/sinon/stub.js
Expand Up @@ -6,6 +6,7 @@ var spy = require("./spy");
var extend = require("./util/core/extend");
var functionToString = require("./util/core/function-to-string");
var getPropertyDescriptor = require("./util/core/get-property-descriptor");
var isEsModule = require("./util/core/is-es-module");
var wrapMethod = require("./util/core/wrap-method");
var stubEntireObject = require("./stub-entire-object");
var throwOnFalsyObject = require("./throw-on-falsy-object");
Expand All @@ -18,6 +19,10 @@ function stub(object, property) {
throw new TypeError("stub(obj, 'meth', fn) has been removed, see documentation");
}

if (isEsModule(object)) {
throw new TypeError("ES Modules cannot be stubbed");
}

throwOnFalsyObject.apply(null, arguments);

if (object && typeof property !== "undefined" && !(property in object)) {
Expand Down
16 changes: 16 additions & 0 deletions lib/sinon/util/core/is-es-module.js
@@ -0,0 +1,16 @@
"use strict";

/**
* Verify if an object is a ECMAScript Module
*
* As the exports from a module is immutable we cannot alter the exports
* using spies or stubs. Let the consumer know this to avoid bug reports
* on weird error messages.
*/
module.exports = function (object) {
return (
object &&
typeof Symbol !== "undefined" &&
object[Symbol.toStringTag] === "Module"
);
};

0 comments on commit d7fb7d5

Please sign in to comment.