How does jest allow mutation of modules? - jestjs

In this question that I asked here:
Why does mutating a module update the reference if calling that module from another module, but not if calling from itself?
I'm asking about the nature of module mutation.
However as it it turns out, ES6 modules can't actually be mutated - all of their properties are treated as constants. (See this answer)
But somehow - when Jest tests modules - they can be mutated, and that's how Jest allows for mocking.
How is this happening?
I imagine that it's a babel plugin that that's running - transpiling the module to CommonJS modules? Is there any documentation about this?
Is there a way to view the transpiled code?

ES6 modules can't actually be mutated - all of their properties are treated as constants.
Interesting. You're right, even something as simple as this:
import * as lib from "./lib"; // import an ES6 module
const spy = jest.spyOn(lib, 'someFunc'); // spy on someFunc
...technically shouldn't be allowed since jest.spyOn replaces the method on the object with a spy and lib.someFunc should be a binding to someFunc in the ES6 module.
But somehow - when Jest tests modules - they can be mutated, and that's how Jest allows for mocking.
How is this happening?
They can only be mutated because Jest isn't actually using ES6 modules.
(I guess for completeness it might be possible to run Jest using actual ES6 modules by using Node's experimental support for ES6 Modules but I haven't tried).
I imagine that it's a babel plugin that that's running - transpiling the module...Is there any documentation about this?
"babel-jest is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the transform configuration option".
So by default Jest will use babel-jest which transpiles the source code using babel (and does a few other things like hoisting calls to jest.mock).
Note that Jest can be also be configured using transform which maps "regular expressions to paths to transformers".
Is there a way to view the transpiled code?
Yes. Transformations are done in jest-runtime here and the output is saved to a cache here.
The easiest way to look at the transpiled code is to view the cache.
You can do that by running Jest with the --showConfig option which will output the config used when running Jest. The cache location can be found by looking at the value of "cacheDirectory".
Then run Jest with the --clearCache option to clear out the cache.
Finally, run Jest normally and the cache directory will contain the transpiled code for your project.
Example
The latest Jest (v24) will transpile this code:
// lib.js
export const someFunc = () => 1;
// code.js
import { someFunc } from './lib';
export const func = () => someFunc() + 1;
// code.test.js
import { func } from './code';
import * as lib from './lib';
test('func', () => {
const spy = jest.spyOn(lib, 'someFunc');
func();
expect(spy).toHaveBeenCalled(); // SUCCESS
});
...to this:
// lib.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.someFunc = void 0;
const someFunc = () => 1;
exports.someFunc = someFunc;
// code.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.func = void 0;
var _lib = require("./lib");
const func = () => (0, _lib.someFunc)() + 1;
exports.func = func;
// code.test.js
"use strict";
var _code = require("./code");
var lib = _interopRequireWildcard(require("./lib"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
test('func', () => {
const spy = jest.spyOn(lib, 'someFunc');
(0, _code.func)();
expect(spy).toHaveBeenCalled(); // SUCCESS
});
The import * as lib from 'lib'; line gets handled by _interopRequireWildcard which uses require under the hood.
Every call to require "will get exactly the same object returned, if it would resolve to the same file" so code.js and code.test.js are getting the same object from require('./lib').
someFunc is exported as exports.someFunc which allows it to be reassigned.
So yes, you're exactly right. Spying (or mocking) like this only works because the ES6 modules are getting transpiled by babel into Node modules in a way that allows them to be mutated.

Related

Gulp + Browserify + TypeScript To Browser

My problem is the following:
I use gulp+browserify to compile my TypeScript to JavaScript that you can use on normal HTML pages, the problem is that my class is never available on the browser:
VM633:1 Uncaught ReferenceError: Test is not defined
at <anonymous>:1:13
This is my TypeScript File:
class Test {
public test(): void {
console.log("aa");
}
}
This is my gulpfile
var gulp = require("gulp");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");
gulp.task("default", function () {
return browserify({
//basedir: '.',
debug: true,
entries: ['app/Resources/typescript/Test.ts'],
cache: {},
packageCache: {}
})
.plugin(tsify)
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest("web/bundles/framework/js"));
});
The file compiles without problem, and is included in my index.html (the compiled js file).
But when i try:
var t = new Test();
I get the following error:
VM633:1 Uncaught ReferenceError: Test is not defined
at <anonymous>:1:13
I can't resolve it, I have read a lot and I haven't found anything clear, I tried all and nothing worked.
There are a few things missing here:
If you want your class to be accessible outside of your module, you have to export it:
export class Test {
// ...
}
Browserify creates functions on top of the classes you define. So it won't be accessible globally (which is a good thing). Normally you would import it in another file and use it:
// in any TS file that wants to use `Test` class. Make sure this is included in the gulp entries as well
import {Test} from "test";
var t = new Test();
console.log(t);
Or if really want it to be accessible globally, you can attach it to window object:
// In Test.ts file:
(window as any).Test = Test; // This can be useful when debuging. But don't do this in production code.

module.exports vs. export default in Node.js and ES6

What is the difference between Node's module.exports and ES6's export default? I'm trying to figure out why I get the "__ is not a constructor" error when I try to export default in Node.js 6.2.2.
What works
'use strict'
class SlimShady {
constructor(options) {
this._options = options
}
sayName() {
return 'My name is Slim Shady.'
}
}
// This works
module.exports = SlimShady
What doesn't work
'use strict'
class SlimShady {
constructor(options) {
this._options = options
}
sayName() {
return 'My name is Slim Shady.'
}
}
// This will cause the "SlimShady is not a constructor" error
// if in another file I try `let marshall = new SlimShady()`
export default SlimShady
The issue is with
how ES6 modules are emulated in CommonJS
how you import the module
ES6 to CommonJS
At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?
Many people consider module.exports = ... to be equivalent to export default ... and exports.foo ... to be equivalent to export const foo = .... That's not quite true though, or at least not how Babel does it.
ES6 default exports are actually also named exports, except that default is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:
// input
export const foo = 42;
export default 21;
// output
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var foo = exports.foo = 42;
exports.default = 21;
Here we can see that the default export becomes a property on the exports object, just like foo.
Import the module
We can import the module in two ways: Either using CommonJS or using ES6 import syntax.
Your issue: I believe you are doing something like:
var bar = require('./input');
new bar();
expecting that bar is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default property!
So in order to access the default export we actually have to do
var bar = require('./input').default;
If we use ES6 module syntax, namely
import bar from './input';
console.log(bar);
Babel will transform it to
'use strict';
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
console.log(_input2.default);
You can see that every access to bar is converted to access .default.
Felix Kling did a great comparison on those two, for anyone wondering how to do an export default alongside named exports with module.exports in nodejs
module.exports = new DAO()
module.exports.initDAO = initDAO // append other functions as named export
// now you have
let DAO = require('_/helpers/DAO');
// DAO by default is exported class or function
DAO.initDAO()
You need to configure babel correctly in your project to use export default and export const foo
npm install --save-dev #babel/plugin-proposal-export-default-from
then add below configration in .babelrc
"plugins": [
"#babel/plugin-proposal-export-default-from"
]

Cannot browserify exports default statement [duplicate]

Before, babel would add the line module.exports = exports["default"]. It no longer does this. What this means is before I could do:
var foo = require('./foo');
// use foo
Now I have to do this:
var foo = require('./foo').default;
// use foo
Not a huge deal (and I'm guessing this is what it should have been all along).
The issue is that I have a lot of code that depended on the way that things used to work (I can convert most of it to ES6 imports, but not all of it). Can anyone give me tips on how to make the old way work without having to go through my project and fix this (or even some instruction on how to write a codemod to do this would be pretty slick).
Thanks!
Example:
Input:
const foo = {}
export default foo
Output with Babel 5
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var foo = {};
exports["default"] = foo;
module.exports = exports["default"];
Output with Babel 6 (and es2015 plugin):
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var foo = {};
exports["default"] = foo;
Notice that the only difference in the output is the module.exports = exports["default"].
Edit
You may be interested in this blogpost I wrote after solving my specific issue: Misunderstanding ES6 Modules, Upgrading Babel, Tears, and a Solution
If you want CommonJS export behavior, you'll need to use CommonJS directly (or use the plugin in the other answer). This behavior was removed because it caused confusion and lead to invalid ES6 semantics, which some people had relied on e.g.
export default {
a: 'foo'
};
and then
import {a} from './foo';
which is invalid ES6 but worked because of the CommonJS interoperability behavior you are describing. Unfortunately supporting both cases isn't possible, and allowing people to write invalid ES6 is a worse issue than making you do .default.
The other issue was that it was unexpected for users if they added a named export in the future, for example
export default 4;
then
require('./mod');
// 4
but
export default 4;
export var foo = 5;
then
require('./mod')
// {'default': 4, foo: 5}
You can also use this plugin to get the old export behavior back.
For library authors you may be able to work around this problem.
I usually have an entry point, index.js, which is the file I point to from the main field in package.json. It does nothing other than re-export the actual entry point of the lib:
export { default } from "./components/MyComponent";
To workaround the babel issue, I changed this to an import statement and then assign the default to module.exports:
import MyComponent from "./components/MyComponent";
module.exports = MyComponent;
All my other files stay as pure ES6 modules, with no workarounds. So only the entry point needs a change slightly :)
This will work for commonjs requires, and also for ES6 imports because babel doesn't seem to have dropped the reverse interop (commonjs -> es6). Babel injects the following function to patch up commonjs:
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
I've spent hours battling this, so I hope this saves someone else the effort!
I have had such kind of issue. And this is my solution:
//src/arithmetic.js
export var operations = {
add: function (a, b) {
return a + b;
},
subtract: function (a, b) {
return a - b;
}
};
//src/main.js
import { operations } from './arithmetic';
let result = operations.add(1, 1);
console.log(result);

Not able to load AMD modules through Jest

I'm trying to use Jest for unit testing my React code but I'm also using requirejs and so all my React code is in AMD modules. It obviously works well in browser but when I run Jest tests, it can't load my AMD modules.
Initially it was giving me error for define saying define is not defined, so I used amdefine by Requirejs to fix it. Now it can understand define but still can't load my module.
I had the same problem today and here is what I've done :
Module.js
(()=> {
const dependencies = ['./dep.js'];
const libEnv = function (dep) {
// lib content
function theAnswer (){
return dep.answer;
}
return {theAnswer}; // exports
};
//AMD & CommonJS compatibility stuff
// CommonJS
if (typeof module !== 'undefined' && typeof require !== 'undefined'){
module.exports = libEnv.apply(this, dependencies.map(require));
module.exports.mockable = libEnv; // module loader with mockable dependencies
}
// AMD
if (typeof define !== 'undefined') define(dependencies, libEnv);
})();
You will found all needed files on my github repository to test :
in browser for requirejs
with node for jest
https://github.com/1twitif/testRequireJSAmdModulesWithJest
I ran into same problem, so I went ahead and mocked my dependency at the top of test file:
jest.mock('../../components/my-button', () => {
// mock implementation
})
import MyButton from '../../components/my-button';
This way, when MyButton is loaded, its dependency is already mocked, so it won't try to load the RequireJS module.
There's no official Facebook support for requirejs in Jest yet. But's planned. Look this thread:
https://github.com/facebook/jest/issues/17
Also in this thread Sterpe posted a plugin he wrote to do it (but I didn't try it):
https://github.com/sterpe/jest-requirejs

If I use `module("somelib")` in typescript, it can't be running in browser

I'm trying to use typescript with angularjs in the client-side.
I found if I use external modules, the generated js won't be run in browser.
controllers.ts
/// <reference path="./libs/underscore.d.ts"/>
import _ = module("underscore");
module test {
export class Ctrl {
constructor($scope:any) {
$scope.name = "Freewind";
_.each($scope.name, function(item) {});
}
}
}
The generated js will be:
var _ = require("underscore")
var test;
(function (test) {
var Ctrl = (function () {
function Ctrl($scope) {
$scope.name = "Freewind";
_.each($scope.name, function (item) {
});
}
return Ctrl;
})();
test.Ctrl = Ctrl;
})(test || (test = {}));
Which can't run correctly. But if I remove the module("underscore") part, it will be OK.
Since I have add underscore.js in the HTML, I think it should be something wrong with the require() method. How to fix it?
There are two ways to load stuff in your HTML pages.
Bundling
The first one is to manually include all the script files in your page. You might run some kind of pre-release step to merge and minify your code - but you're taking responsibility for that instead of leaving it to the code to do. This is generally called bundling.
In the case on bundling, you only use references in your TypeScript code (not imports), like this:
/// <reference path="./libs/underscore.d.ts"/>
module test {
export class Ctrl {
constructor($scope:any) {
$scope.name = "Freewind";
_.each($scope.name, function(item) {});
}
}
}
Module loading
If you want to use a module loader, which for The Web is typically RequireJS, you can load External Modules using the import statement. Normally you wouldn't need the reference in this case...
import _ = module("./libs/underscore");
module test {
export class Ctrl {
constructor($scope:any) {
$scope.name = "Freewind";
_.each($scope.name, function(item) {});
}
}
}
RequireJS with non-modules
There is a third scenario, which is quite common. If you intend to import something that isn't an External Module (such as jQuery, but underscore may also fit this pattern), you are better off using a reference and a manual call to RequireJS.
RequireJS will load the dependency for you, so you would wrap your main program with it (which would probably be in a separate file such as app.ts.
///<reference path="./libs/require.d.ts" />
///<reference path="./libs/underscore.d.ts" />
module test {
export class Ctrl {
constructor($scope:any) {
$scope.name = "Freewind";
_.each($scope.name, function(item) {});
}
}
}
require(['underscore'], function (_) {
var ctrl = new test.Crtl({});
});
You can also use require.config to specify the path to underscore in your application.
require.config({
paths: {
"underscore": "libs/underscore"
}
});
When you use require, you asserting that underscore is exported as a loadable module. This further assumes that you are using some sort of module loader system (TypeScript currently supports AMD and CommonJS modules). Since you aren't using a module system, and underscore is simply available in global scope, you can use a /// reference to tell TypeScript that Underscore is available in global scope. Put the following at the top of your file:
/// <reference path="./libs/underscore.d.ts">
And you should be good to go!

Resources