Skip to content

Commit d7fb7d5

Browse files
authored
Merge pull request #1715 from sinonjs/sinon-es6-module-detection
Throw meaningful error stubbing ECMAScript Module
2 parents b491a57 + 51cdafe commit d7fb7d5

9 files changed

+373
-1187
lines changed

lib/sinon/spy.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ var functionToString = require("./util/core/function-to-string");
88
var getPropertyDescriptor = require("./util/core/get-property-descriptor");
99
var sinonMatch = require("./match");
1010
var deepEqual = require("./util/core/deep-equal").use(sinonMatch);
11+
var isEsModule = require("./util/core/is-es-module");
1112
var spyCall = require("./call");
1213
var wrapMethod = require("./util/core/wrap-method");
1314
var sinonFormat = require("./util/core/format");
@@ -25,12 +26,16 @@ var callId = 0;
2526
function spy(object, property, types) {
2627
var descriptor, methodDesc;
2728

29+
if (isEsModule(object)) {
30+
throw new TypeError("ES Modules cannot be spied");
31+
}
32+
2833
if (!property && typeof object === "function") {
2934
return spy.create(object);
3035
}
3136

3237
if (!object && !property) {
33-
return spy.create(function () { });
38+
return spy.create(function () {});
3439
}
3540

3641
if (!types) {

lib/sinon/stub.js

+5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ var spy = require("./spy");
66
var extend = require("./util/core/extend");
77
var functionToString = require("./util/core/function-to-string");
88
var getPropertyDescriptor = require("./util/core/get-property-descriptor");
9+
var isEsModule = require("./util/core/is-es-module");
910
var wrapMethod = require("./util/core/wrap-method");
1011
var stubEntireObject = require("./stub-entire-object");
1112
var throwOnFalsyObject = require("./throw-on-falsy-object");
@@ -18,6 +19,10 @@ function stub(object, property) {
1819
throw new TypeError("stub(obj, 'meth', fn) has been removed, see documentation");
1920
}
2021

22+
if (isEsModule(object)) {
23+
throw new TypeError("ES Modules cannot be stubbed");
24+
}
25+
2126
throwOnFalsyObject.apply(null, arguments);
2227

2328
if (object && typeof property !== "undefined" && !(property in object)) {

lib/sinon/util/core/is-es-module.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"use strict";
2+
3+
/**
4+
* Verify if an object is a ECMAScript Module
5+
*
6+
* As the exports from a module is immutable we cannot alter the exports
7+
* using spies or stubs. Let the consumer know this to avoid bug reports
8+
* on weird error messages.
9+
*/
10+
module.exports = function (object) {
11+
return (
12+
object &&
13+
typeof Symbol !== "undefined" &&
14+
object[Symbol.toStringTag] === "Module"
15+
);
16+
};

0 commit comments

Comments
 (0)