jestjs / jest Goto Github PK
View Code? Open in Web Editor NEWDelightful JavaScript Testing.
Home Page: https://jestjs.io
License: MIT License
Delightful JavaScript Testing.
Home Page: https://jestjs.io
License: MIT License
When adding Jest to an existing project it breaks on the first run with the default (mac) ulimit of 256 files.
This can be solved by running:
ulimit -n 10000 # or some other big value
Otherwise, jest will just keep throwing errors trying to open modules, either jest's own dependencies or others.
npm test
throws "cannot read property ref
of null" when my test requires React addons
# Coffeescript
describe 'Root', ->
it 'should switch content when navigating', ->
React = require 'react/addons'
Running on OS X Mavericks
npm -v 1.4.9
node -v 0.10.28
Full stacktrace:
http://pastebin.com/aCgmYcuv
See also: http://stackoverflow.com/q/24216958
I ran into this same problem today. Jest doesn't seem to respect the "dontMock" on the "debug" package from npm.
Jasmine
Jasmine
In a spec:
console.log {a: {b: 'c'}}
Output:
{"a":"{\"b\":\"c\"}"}
It's really unintuitive that you should put your require()s either in your specs or in your beforeEach() (because jest clears the module registry cache in between each spec).
We should see if we can alleviate confusion here by console.warn()ing when a require() happens outside of an it() or a beforeEach() function
Now the problem is when testing with Jest, the non-existed key's value in an object doesn't equal to undefined.
For example:
my_obj = {a:1};
my_obj['b']===undefined; // should return true, but when test with jest, it returns false.
my_obj['b']===jasmine.undefined; //this returns true
react.js check mergeObjectsWithNoDuplicateKeys for return values of all getInitialState() calls.
https://github.com/facebook/react/blob/master/src/core/ReactCompositeComponent.js#L574
If I change the code from:
one[key] === undefined
to:
one[key] === jasmine.undefined
Then it works. Any idea how to fix it? Thanks!
$ jest -o
Using Jest CLI v0.1.11
Looking for changed files...
/usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:126
throw e;
^
Error: Please run node with the --harmony flag!
at new Loader (/usr/local/lib/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:131:13)
at /usr/local/lib/node_modules/jest-cli/src/TestRunner.js:100:12
at _fulfilled (/usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:798:54)
at self.promiseDispatch.done (/usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:827:30)
at Promise.promise.promiseDispatch (/usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:760:13)
at /usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:574:44
at flush (/usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:108:17)
at process._tickCallback (node.js:419:13)
I think that line might blame to me with ES6 WeakMaps...
Consider this test:
describe('SomeTest', function() {
it("requires underscore (unmocked) and jQuery (mocked)", function() {
jest.dontMock('underscore');
var _ = require('underscore'),
jQuery = require('jquery');
expect(_.mock).toBeUndefined();
expect(jQuery.mock).toBeDefined();
})
});
It fails because jQuery.mock
is undefined
.
The issue can easily reproduced by slightly modifying the included examples/tutorial/__test__/fetchCurrentUser-test.js
, dropping in a single dontMock('underscore')
call:
// fetchCurrentUser-test.js, l.4-11
it('calls into $.ajax with the correct params', function() {
jest.dontMock('underscore');
var $ = require('jquery');
var fetchCurrentUser = require('../fetchCurrentUser');
// Call into the function we want to test
function dummyCallback() {}
fetchCurrentUser(dummyCallback);
The test will now fail since jQuery is no longer mocked.
The root cause for this is that HasteModuleLoader._getNormalizedModuleID()
seems to be returning user::
for any module in node_modules
, making dontMock
effectively disable auto-mocking for all npm-installed modules.
webpack can be installed globally, but it delegates to a locally-installed version if one exists:
Perhaps we should consider the same so that people can use the jest
command easily instead of npm test
.
When using CoffeeScript in Node or Browserify you can use require './somefile'
and it will check for somefile.coffee
, somefile.litcoffee
, and somefile.coffee.md
. Jest does not look for these extensions and simply throws a Cannot find module
error.
To reproduce this:
examples/coffeescript/common.coffee
. It can be an empty file, it just should exist.sum.coffee
with the code below.coffee sum.coffee
and see that you get get the output 11
npm test
. It will throw the Cannot find module
error.# It doesn't matter what this module does, it just matters that the extension
# isn't specified. This will work in NodeJS and Browserify
require './common'
sum = (a, b) ->
a + b
module.exports = sum
# I just added this so you can run `coffee sum.coffee`
# to demonstrate that this is working outside of jest.
if require.main is module
console.log sum(5, 6)
jsdom
is painfully slow and has native dependencies. It would be great if jest would support using the domino
DOM implementation instead: https://github.com/fgnass/domino
I encountered this testing code that require'd the superagent module and caused jest to crash. Relevant portions of superagent's package.json are:
"dependencies": {
...
"component-emitter": "1.1.2",
"reduce-component": "1.0.1"
},
"main": "./lib/node/index.js",
"browser": {
"./lib/node/index.js": "./lib/client.js",
"emitter": "component-emitter",
"reduce": "reduce-component"
},
This example causes two issues for jest:
emitter
and reduce
I recognize handling various non-standard extensions to package.json is potentially outside the scope of the project but thought it worth mentioning.
This seems similar to #20 but significantly broader. Similar to the older issue, with the latest version of Jest on NPM (tagged v0.1.15), this fails:
describe('SomeTest', function() {
it("requires underscore (unmocked) and jQuery (mocked)", function() {
jest.dontMock('underscore');
var _ = require('underscore');
var $ = require('jquery');
expect(_.mock).toBeUndefined();
expect($.mock).toBeDefined();
})
});
Found 1 matching tests...
FAIL test/client/bug-test.js (0.062s)
● SomeTest › it requires underscore (unmocked) and jQuery (mocked)
- Expected undefined to be defined.
at Spec.<anonymous> (/Users/cody/Coding/elephant_project/app/test/client/bug-test.js:9:24)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
1 tests failed, 0 tests passed (1 total)
Run time: 1.003s
However, this works:
describe('SomeTest', function() {
it("requires underscore (unmocked) and jQuery (mocked)", function() {
jest.dontMock('underscore');
var _ = require('underscore');
jest.mock('jquery')
var $ = require('jquery');
expect(_.mock).toBeUndefined();
expect($.mock).toBeDefined();
})
});
HOWEVER, contrary to the initial bug report, this seems to be affecting more than just NPM modules. In fact, this works:
var App = require('../../src/client/code/app/app.js');
describe('test 1', function() {
return it('should', function() {
expect(App.mock).toBeDefined();
});
});
But this fails:
jest.dontMock('jquery');
var App = require('../../src/client/code/app/app.js');
describe('test 1', function() {
return it('should', function() {
return expect(App.mock).toBeDefined();
});
});
As does this:
jest.dontMock('../../src/client/code/app/app.js');
var $ = require('jquery');
describe('test 1', function() {
return it('should', function() {
return expect($.mock).toBeDefined();
});
});
In short: Calling .dontMock() on an ANY module seems to disable mocking on ALL modules thereafter.
This one's very odd. It seems you can't run two jest tests involving a component which uses the focus()
method on a <textarea>
element. (I warned you, very odd.)
Sample react component:
/** @jsx React.DOM */
var React = require("react");
var Plop = React.createClass({
componentDidMount: function() {
this.getDOMNode().querySelector("textarea").focus();
},
render: function() {
return <div><textarea /></div>;
}
});
module.exports = Plop;
Sample test:
/** @jsx React.DOM */
var TestUtils = require('react/addons').addons.TestUtils;
jest.dontMock('../plop');
var Plop = require('../plop');
describe("test", function() {
it("should run a first time", function() {
TestUtils.renderIntoDocument(<Plop />);
});
});
This one passes just fine:
Found 1 matching tests...
PASS __tests__/bug-test.js (0.909s)
1 tests passed (1 total)
Now update the test suite adding another test:
/** @jsx React.DOM */
var TestUtils = require('react/addons').addons.TestUtils;
jest.dontMock('../plop');
var Plop = require('../plop');
describe("test", function() {
it("should run a first time", function() {
TestUtils.renderIntoDocument(<Plop />);
});
it("should run a second time", function() {
TestUtils.renderIntoDocument(<Plop />);
});
});
This new suite fails:
Found 1 matching tests...
FAIL __tests__/bug-test.js (0.924s)
● test › it should run a second time
- TypeError: Object [object global] has no method 'getSelection'
at getModernOffsets (/Users/niko/tmp/jest-bug/node_modules/react/lib/ReactDOMSelection.js:62:26)
at Object.ReactDOMSelection.getOffsets (/Users/niko/tmp/jest-bug/node_modules/react/lib/ReactDOMSelection.js:176:12)
at Object.ReactInputSelection.getSelection (/Users/niko/tmp/jest-bug/node_modules/react/lib/ReactInputSelection.js:107:37)
at ReactReconcileTransaction.ReactInputSelection.getSelectionInformation (/Users/niko/tmp/jest-bug/node_modules/react/lib/ReactInputSelection.js:53:31)
at ReactReconcileTransaction.Mixin.initializeAll (/Users/niko/tmp/jest-bug/node_modules/react/lib/Transaction.js:197:30)
at ReactReconcileTransaction.Mixin.perform (/Users/niko/tmp/jest-bug/node_modules/react/lib/Transaction.js:158:12)
at ReactComponent.Mixin.mountComponentIntoNode (/Users/niko/tmp/jest-bug/node_modules/react/lib/ReactComponent.js:537:19)
at Object.ReactMount._renderNewRootComponent (/Users/niko/tmp/jest-bug/node_modules/react/lib/ReactMount.js:309:25)
at Object._renderNewRootComponent (/Users/niko/tmp/jest-bug/node_modules/react/lib/ReactPerf.js:57:21)
at Object.ReactMount.renderComponent (/Users/niko/tmp/jest-bug/node_modules/react/lib/ReactMount.js:359:32)
at Object.renderComponent (/Users/niko/tmp/jest-bug/node_modules/react/lib/ReactPerf.js:57:21)
at Object.ReactTestUtils.renderIntoDocument (/Users/niko/tmp/jest-bug/node_modules/react/lib/ReactTestUtils.js:57:18)
at Spec.<anonymous> (/Users/niko/tmp/jest-bug/__tests__/bug-test.js:15:15)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
Side note, after investigating a little, it seems that ReactDOMSelection
relies on window.getSelection
for some stuff, but that jsdom doesn't support it (hence the error we get.)
Maybe you should start thinking of implementing required polyfills in jest/jsdom to match modern environments? (yeah, I know, tedious.)
Note: I've titled this bug with the exception string to help indexing this issue for people searching for the exact error message, feel free to rephrase if needed.
If you install a package with npm -g
(e.g. maybe the module is stateful and needs to be shared by all dependents), Haste currently fails since it looks for the module under the local node_modules.
Async support in Jasmine 1.3 is pretty poor, this has been fixed in version 2 of the framework. Maybe we should consider upgrading to that version.
I cloned the repo and was unable to get the React test to run. I followed the instructions on the Jest page. Below is the result of running npm test
@ test /Users/evankline/Documents/reactprac/jest/examples/react
node ../../bin/jest.js
Using Jest CLI v0.1.8
Found 1 matching tests...
Every it
statement, even if the corresponding function is blank, adds roughly 0.2 – 0.5s to the runtime of npm test
. Observed by commenting statements in and out.
OS X 10.9.3
npm -v 1.4.9
node -v 0.10.28
Tests are in Coffeescript, set up as described in the tutorial
These tests all pass when the rootDir
setting in package.json is removed. With the rootDir setting:
npm modules are not mocked with only:
jest.autoMockOff()
npm modules are unexpectedly mocked with both:
jest.autoMockOff()
jest.mock('some-npm-module')
npm modules are not mocked with all three:
jest.autoMockOff()
jest.mock('some-npm-module')
jest.dontMock('some-other-npm-module')
Repository with runnable example: https://github.com/lrowe/jest-autoMock-bug
Possibly related to #72.
I see that the --o switch exists to only test git diffed files, but it would be a useful feature to add a --match or --filter argument to only run tests matching the passed patterns.
Unmocking becomes really cumbersome when the module uses something like 'lodash.bla' (as an independent npm module) because of all the subdependencies you need to unmock (it currently fails, calling a mock and getting an undefined
return value and all); this is an implementation detail that I shouldn't have to configure in my own test.
Currently there's jest.autoMockOff()
, but I'm not sure whether it'd be a better idea to have a dontMockWholeSubtree
or something. Wouldn't that be more flexible?
Here's a very simple example showing how requiring Backbone will cause Jest to fail.
https://github.com/maspwr/backbone-jest/tree/master
TypeError: /Users/mark/projects/gitp/backbone-jest/__tests__/FailingTest.js: Cannot read property 'protocol' of undefined
at Location.protocol (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/node_modules/jsdom/lib/jsdom/browser/location.js:18:36)
at _getMetadata (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/lib/moduleMocker.js:279:49)
at _getMetadata (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/lib/moduleMocker.js:286:23)
at _getMetadata (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/lib/moduleMocker.js:279:27)
at _getMetadata (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/lib/moduleMocker.js:279:27)
at _getMetadata (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/lib/moduleMocker.js:279:27)
at Object.module.exports.getMetadata (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/lib/moduleMocker.js:388:20)
at Loader._generateMock (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:280:56)
at Loader.requireMock (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:782:43)
at Loader.requireModuleOrMock (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:897:17)
at /Users/mark/projects/gitp/backbone-jest/__tests__/FailingTest.js:1:83
at Object.runContentWithLocalBindings (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/lib/utils.js:309:17)
at Loader._execModule (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:243:9)
at Loader.requireModule (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:879:10)
at jasmineTestRunner (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/jasmineTestRunner/jasmineTestRunner.js:225:16)
at /Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/TestRunner.js:369:12
at _fulfilled (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/node_modules/q/q.js:798:54)
at self.promiseDispatch.done (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/node_modules/q/q.js:827:30)
at Promise.promise.promiseDispatch (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/node_modules/q/q.js:760:13)
at /Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/node_modules/q/q.js:574:44
at flush (/Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/node_modules/q/q.js:108:17)
at /Users/mark/projects/gitp/backbone-jest/node_modules/jest-cli/src/lib/FakeTimers.js:234:7
at process._tickCallback (node.js:419:13)
This issue is to document my failings and success with require-ing non-JavaScript files and making it work with Jest. The following text is a precursor with lots of stacktraces which might help someone else stumble upon this simple solution, while the solution is presented at the bottom.
When calling require()
with anything that doesn't return JavaScript, jest exits with a syntax error:
- SyntaxError: /Users/arnihermann/Code/jest-test/Foo.js: /Users/arnihermann/Code/jest-test/Foo.css: Unexpected token .
at Contextify.sandbox.run (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/node_modules/jsdom/node_modules/contextify/lib/contextify.js:12:24)
at JSDomEnvironment.runSourceText (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/JSDomEnvironment.js:90:22)
at Object.runContentWithLocalBindings (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/lib/utils.js:279:23)
at Loader._execModule (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:242:9)
at Loader.requireModule (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:853:10)
at Loader._generateMock (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:273:30)
at Loader.requireMock (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:756:43)
at Loader.requireModuleOrMock (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:871:17)
at /Users/arnihermann/Code/jest-test/Foo.js:2:1
at Object.runContentWithLocalBindings (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/lib/utils.js:295:17)
I'm using webpack on a React project of mine which has a simple preprocessor.js
as provided by the React example:
/**
* a `jest` preprocessor for jsx files
*/
var ReactTools = require('react-tools');
module.exports = {
process: function(src) {
return ReactTools.transform(src);
}
};
When I try and require non-JavaScript (e.g. css) files when this preprocessor is enabled, I get something like the following error message:
- Error: /Users/arnihermann/Code/jest-test/Foo.js: /Users/arnihermann/Code/jest-test/preprocessor.js: Parse Error: Line 1: Unexpected token .
at throwError (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:2154:21)
at throwUnexpected (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:2216:9)
at parsePrimaryExpression (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:2676:16)
at /Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:5832:38
at trackLeftHandSideExpressionAllowCall (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:5732:61)
at parsePostfixExpression (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:2795:20)
at /Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:5832:38
at parseUnaryExpression (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:2859:16)
at /Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:5832:38
at parseBinaryExpression (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:2947:16)
at /Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:5832:38
at parseConditionalExpression (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:2994:16)
at /Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:5832:38
at parseAssignmentExpression (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:3179:16)
at /Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:5832:38
at parseExpression (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:3220:16)
at /Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:5832:38
at parseStatement (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:4133:16)
at /Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:5832:38
at parseSourceElement (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:4682:20)
at parseProgramElement (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:4700:16)
at parseProgramElements (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:4732:29)
at parseProgram (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:4779:16)
at /Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:5832:38
at Object.parse (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/esprima-fb/esprima.js:6252:23)
at transform (/Users/arnihermann/Code/jest-test/node_modules/react-tools/node_modules/jstransform/src/jstransform.js:215:19)
at Object.module.exports.transform (/Users/arnihermann/Code/jest-test/node_modules/react-tools/main.js:14:12)
at Object.module.exports.process (/Users/arnihermann/Code/jest-test/preprocessor.js:8:23)
at Object.readAndPreprocessFileContent (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/lib/utils.js:266:53)
at Loader._execModule (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:206:11)
at Loader.requireModule (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:853:10)
at Loader.requireModuleOrMock (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:873:17)
at /Users/arnihermann/Code/jest-test/Foo.js:2:1
at Object.runContentWithLocalBindings (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/lib/utils.js:295:17)
at Loader._execModule (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:242:9)
at Loader.requireModule (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:853:10)
at Loader.requireModuleOrMock (/Users/arnihermann/Code/jest-test/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:873:17)
at Spec.<anonymous> (/Users/arnihermann/Code/jest-test/__tests__/Foo-test.js:12:13)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
The solution is changing preprocessor.js
such that Jest interprets non-JavaScript as JavaScript. In my case, I don't care about the contents of the stylesheets in my tests so I discard the contents of those files:
/**
* a `jest` preprocessor for jsx files
*/
var ReactTools = require('react-tools');
module.exports = {
process: function(src, path) {
if (path.match(/\.css$/)) {
return '';
}
return ReactTools.transform(src);
}
};
If you want to do something with the output, make sure to return it as a string literal or some other data structure that will be interpreted as valid JavaScript code.
Thanks to @vjeux for pointing out this simple solution.
Jest is not at fault for this but wanted to point it out here in case it helps someone. The problem is with a config file within Ionic.
The file located in ./plugins/com.ionic.keyboard/package.json looks like this by default
{
"version": "0.0.1",
"name": "com.ionic.keyboard"
"cordova_name": "Keyboard",
"description": "Ionic Keyboard Plugin",
"license": "MIT",
"keywords": [
"ionic",
"keyboard"
],
}
I fixed the comma issues to this and it now works
{
"version": "0.0.1",
"name": "com.ionic.keyboard",
"cordova_name": "Keyboard",
"description": "Ionic Keyboard Plugin",
"license": "MIT",
"keywords": [
"ionic",
"keyboard"
]
}
See 8106ade.
After send pull request here - #18
Travis said that pull request is ready to merge.
This is not true because here: https://travis-ci.org/facebook/jest/jobs/25233025 (build: https://travis-ci.org/facebook/jest/builds/25233024) you can see that one of test has failed (under my windows enviroment all test has passed), and the exit code is 0.
when trying to run jest for the first time (with a test file in src/tests
Using Jest CLI v0.1.10
Found 1 matching tests...
Error reading file: `/Users/hojberg/code/swipely/aviator/node_modules/grunt-browserify/node_modules/watchify/node_modules/browserify/node_modules/browser-pack/node_modules/combine-source-map/node_modules/convert-source-map/package.json`
/usr/local/lib/node_modules/jest-cli/node_modules/node-haste/lib/loader/ResourceLoader.js:88
throw err;
^
Error: EMFILE, open '/Users/hojberg/code/swipely/aviator/node_modules/grunt-browserify/node_modules/watchify/node_modules/browserify/node_modules/browser-pack/node_modules/combine-source-map/node_modules/convert-source-map/package.json'
Not sure if my setup is weird in some way - hope you guys have seen this error before and can help me out.
> [email protected] test /Users/khotchkiss/Work/Sites/ball
> jest
Found 1 matching tests...
Error reading file: `/Users/khotchkiss/Work/Sites/ball/node_modules/gulp-csso/node_modules/gulp-util/node_modules/lodash.template/node_modules/lodash.keys/node_modules/lodash._shimkeys/node_modules/lodash._objecttypes/package.json`
/Users/khotchkiss/Work/Sites/ball/node_modules/jest-cli/node_modules/node-haste/lib/loader/ResourceLoader.js:88
throw err;
^
Error: EMFILE, open '/Users/khotchkiss/Work/Sites/ball/node_modules/gulp-csso/node_modules/gulp-util/node_modules/lodash.template/node_modules/lodash.keys/node_modules/lodash._shimkeys/node_modules/lodash._objecttypes/package.json'
Every time I run the jest
/npm test
command, I get an EMFILE
as Jest appears to be going through my node_modules
folder, trying to look for tests. Using a build system, I have tons of modules that are just there to help me locally (but the issue still persists when I install modules via npm install --production
) Is it possible to ignore node_modules or drop in Isaac's graceful FS module somewhere? It's hard to run tests without node_modules
but currently impossible for me to run tests with node_modules
present.
This issue occurs regardless of which folder I'm in - so if I got to the folder _tests__
is in, I still get it.
(I know I can raise the amount of files node can open via sysctl -w kern.maxfiles=20480
but that's not ideal, I'd rather just ignore node_modules)
Just upgrade node/npm and seeing this:
npm http 404 https://registry.npmjs.org/node-haste/-/node-haste-1.2.3.tgz
npm ERR! fetch failed https://registry.npmjs.org/node-haste/-/node-haste-1.2.3.tgz
npm ERR! Error: 404 Not Found
npm ERR! at WriteStream.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/fetch.js:58:12)
npm ERR! at WriteStream.EventEmitter.emit (events.js:117:20)
npm ERR! at fs.js:1598:14
npm ERR! at /usr/local/lib/node_modules/npm/node_modules/graceful-fs/graceful-fs.js:105:5
npm ERR! at Object.oncomplete (fs.js:107:15)
npm ERR! If you need help, you may report this *entire* log,
npm ERR! including the npm and node versions, at:
npm ERR! <http://github.com/npm/npm/issues>
npm ERR! System Darwin 13.1.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "jest-cli" "--save-dev"
npm ERR! cwd /Users/josephmisiti/projects/machinelearning/go-machine-learning
npm ERR! node -v v0.10.28
npm ERR! npm -v 1.4.10
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /Users/josephmisiti/projects/machinelearning/go-machine-learning/npm-debug.log
npm ERR! not ok code 0
(```
There seems to be an issue when using config.rootDir when mocking node_module(s).
folder structure
root
+ client
+ + app
+ + + foo.js
+ + + bar.js
+ + + __tests__
+ + + + test.js
+ node_modules
+ + lodash
+ + kew
+ package.json
root/package.json
{
"jest": {
"rootDir": "client/app"
}
}
root/client/app/tests/test.js:
'use strict';
describe('using config.rootDir', function() {
it('has problems when mocking node_modules', function() {
// lodash and kew have been installed with npm
jest.setMock('lodash', 'lodash');
jest.setMock('kew', 'kew');
console.log(require('lodash'));
console.log(require('kew'));
});
it('works when mocking my own modules', function() {
// ../foo and ../bar are my own modules
jest.setMock('../foo', 'foo');
jest.setMock('../bar', 'bar');
console.log(require('../foo'));
console.log(require('../bar'));
});
});
this yields:
Using Jest CLI v0.1.15
Found 1 matching tests...
PASS __tests__/baz-test.js (0.032s)
kew
kew
foo
bar
1 tests passed (1 total)
Run time: 0.86s
i was expecting:
Using Jest CLI v0.1.15
Found 1 matching tests...
PASS __tests__/baz-test.js (0.032s)
lodash
kew
foo
bar
1 tests passed (1 total)
Run time: 0.86s
I created a small demo repo with a single JS module and a single test.
mkdir moof && cd moof
git init
npm init
npm install --save clamp
touch moof.js
mkdir __tests__ && touch __tests/moof-test.js
git add .
git commit -m 'Initial commit'
Then edit moof.js:
require('clamp')
And moof-test.js:
jest.dontMock('../moof');
describe('moof', function() {
it ('moofs', function() {
var moof = require('../moof');
});
});
Run jest -o
:
$ jest -o
Using Jest CLI v0.1.12
Looking for changed files...
/usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:126
throw e;
^
Error: Cannot find module 'tape' from '/Users/ide/tmp/moof/node_modules/clamp'
at Function.module.exports [as sync] (/usr/local/lib/node_modules/jest-cli/node_modules/resolve/lib/sync.js:32:11)
at Loader._nodeModuleNameToPath (/usr/local/lib/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:472:20)
at Loader._moduleNameToPath (/usr/local/lib/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:447:19)
at Loader._getNormalizedModuleID (/usr/local/lib/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:343:31)
at Loader._getDependencyPathsFromResource (/usr/local/lib/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:302:12)
at Loader.getDependentsFromPath (/usr/local/lib/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:697:34)
at /usr/local/lib/node_modules/jest-cli/src/TestRunner.js:171:35
at _fulfilled (/usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:798:54)
at self.promiseDispatch.done (/usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:827:30)
at Promise.promise.promiseDispatch (/usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:760:13)
at /usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:574:44
at flush (/usr/local/lib/node_modules/jest-cli/node_modules/q/q.js:108:17)
at process._tickCallback (node.js:419:13)
Inside node_modules/clamp
there is a file called test.js that requires tape
. We don't have tape
because it's a dev dependency and also test.js is not needed. Haste should be smarter about the files it scans... this might be tricky because technically one could require clamp/test
(from PHP even...) and it's just hard to statically tell what files are actually used.
13:23 jeffmo: what's the reason behind using toBeCalled rather than jasmine's toHaveBeenCalled?
13:24 <•jeffmo> chenglou: good question on toBeCalled/toHaveBeenCalled — I’ve wondered that myself (it’s just layover from jst really). I suspect it was to leave support for using regular jasmine spies if you wanted to
Hi,
My project uses JSONStream, and because of its index file starts with a shebang, contextify always throws this error when including it:
- SyntaxError: [...]/myfile.js: [...]/tip/node_modules/JSONStream/index.js: Unexpected token ILLEGAL
I could work around that by using this preprocessor:
module.exports = {
process: function(src, path) {
if (path.match(/\.js$/)) {
if (src.length > 2 & src[0] === '#' & src[1] === '!') {
return src.substring(src.indexOf('\n'));
}
}
return src;
}
};
But this should be performed by either contextify (maybe not because it is browser oriented) or jest (maybe more adequate for node.js testing).
The 'use strict' declaration in scripts doesn't seem to have any effect in files or in test files.
module file:
\\ foo.js
(function() {
'use strict';
foo = 'foo value';
module.exports = foo;
}());
and test file:
\\ __tests__\foo-test.js
(function() {
'use strict';
jest.dontMock('../foo.js');
describe('testing use strict', function() {
it('should throw some sort of error', function() {
bar = 'bar value';
console.log(bar);
console.log(require('../foo'));
});
});
}());
running npm test yields:
Using Jest CLI v0.1.15
Found 1 matching tests...
PASS __tests__/foo-test.js (0.03s)
bar value
foo value
More fun that way (instead of just the filename).
I feel like a lot of node projects use lib
and test
as the directory names. It would be nice to be able to keep that convention.
Hi! I think I may have found a bug in jest. When I require a .json file twice in code jest is running, the second require() seems to return undefined. Here's a test that's failing for me, that I would expect to pass:
jest.autoMockOff();
var assert = require("assert");
describe("requiring json", function() {
it("should return the same json from multiple requires", function() {
var version1 = require("../version.json");
var version2 = require("../version.json");
assert.notEqual(version1, undefined);
assert.notEqual(version2, undefined);
assert.deepEqual(version1, version2);
});
});
(where the file ../version.json exists, and the above test passes when run by mocha).
If I understand it correctly, there is currently no way of using this with RequireJS rather than CommonJS style require(). Are there any plans of adding support for RequireJS? Is it even feasible?
Take this example:
// package.json
{
"devDependencies": {
"jest-cli": "~0.1.2" // requires underscore === 1.2.4
},
"dependencies": {
"backbone": "~1.1.2" // requires underscore >= 1.5.0
},
"jest": {
"unmockedModulePathPatterns": {
"./node_modules/backbone"
}
}
}
// test.js, crashes due to '_.has' missing from underscore v1.2.4,
// which is the version required by `jest-cli` that gets mistakenly loaded.
describe("Wrong underscore version", function() {
it("Backbone should load underscore >1.5.0 as specified in its package.json", function(){
var Backbone = require('backbone')
// .extend uses '_.has' which only exists for >1.4.2
expect(Backbone.Collection.extend({})).toBeDefined();
});
});
The reason for this, from what I could gather by stepping through the problem a few times:
jest-cli
needs the precise v1.2.4 of underscore, hence it gets its own underscore version in jest-cli/node_modules/underscoreHasteModuleLoader
creates its _nodeModuleProjectConfigNameToResource
map by calling node-haste's ResourceMap.getAllResourcesByType
function, which uses Object.keys
to get a list of all available resources in arbitrary order.require('underscore')
, it can happen that underscore resolves to jest-cli's version, since it was the last underscore
-resource in the array returned by ResourceMap.getAllResourcesByType
I'm way too confused by npm packaging right now to really propose a solution, but a first workaround might be to loosen up the version requirement for underscore...
Was there a specific reason for deciding to use regular expressions for file path matching instead of glob-like path patterns?
If there is no specific reason, I would be willing to implement path matching via minimatch
. This might make it easier for people coming from grunt or gulp.
It could also potentially allow us to consolidate config.testDirectoryName
, config.testFileExtensions
, config.testPathDirs
and config.testPathIgnorePatterns
into a single option (whether that's better though I cannot say):
{
"testPaths": ["__tests__/**/*.(js|coffee)", "!/node_modules"]
}
(evaluated relative to the <root dir>
)
I'm trying to test a library that, for various reasons, relies on underscore being loaded in the global scope. My first attempt was to write this in a setupEnvScriptFile:
// environment.js
var _ = require("../lib/underscore.js");
I quickly concluded that vars wouldn't be declared in the global scope (which makes sense! just surprised me a tiny bit) so then tried:
// environment.js
global._ = require("../lib/underscore.js");
This doesn't work because global
isn't available in this context. I then figured out that you can define a global by doing:
// environment.js
_ = require("../lib/underscore.js");
but I don't want it mocked, so I did:
// environment.js
jest.dontMock("../lib/underscore.js");
_ = require("../lib/underscore.js");
but that doesn't work because jest
isn't defined! I suppose I could/should use unmockedModulePathPatterns for this, but all of this behavior was surprising to me.
It only happens every so often, but it's super confusing and hard to debug when it does:
If ever a module were to somehow clobber it's exports object with something that isn't an object, you get a nasty error like this:
TypeError: Cannot read property 'ref' of null
at mocks.js:285:11
at visit (mocks.js:275:5)
at removeUnusedRefs (mocks.js:284:3)
at Object.module.exports.getMetadata (mocks.js:364:5)
at mock-modules.js:153:16
at mock-modules.js:128:22
at _generateMock (mock-modules.js:162:20)
at _System._loadAutoMock (mock-modules.js:199:51)
at _System._moduleRequire (mock-modules.js:313:17)
Let's add an assertion earlier on to ensure that the error message is at least helpful.
A common scenario where people hit this is when they're trying to test a react component that look something like this:
var React = require('React');
module.exports = React.createClass({
// ...
});
In this case, if you don't explicitly mark the React
module as unmocked, module.exports
is assigned the return value of React.createClass()
-- which is a mock function, and thus returns undefined
.
Steps to repo:
npm install jquery underscore jest-cli
npm init
and accept all defaults except setting the test command to jest__tests__
describe('SomeTest', function() {
it("requires underscore (unmocked) and jQuery (mocked)", function() {
jest.dontMock('underscore');
var _ = require('underscore');
var $ = require('jquery');
expect(_.mock).toBeUndefined();
expect($.mock).toBeDefined();
})
});
If you run npm test
it will pass, as you'd expect. Now edit the generated package.json to add "jest": {"modulePathIgnorePatterns": ["/node_modules/"]}
, and rerun npm test
. You'll get:
cody@possum jest-test $ npm test
> [email protected] test /Users/cody/Coding/jest-test
> jest
Found 1 matching tests...
FAIL __tests__/test.js (0.058s)
● SomeTest › it requires underscore (unmocked) and jQuery (mocked)
- Expected undefined to be defined.
at Spec.<anonymous> (/Users/cody/Coding/jest-test/__tests__/test.js:8:24)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
1 tests failed, 0 tests passed (1 total)
Run time: 0.761s
npm ERR! Test failed. See above for more details.
npm ERR! not ok code 0
In other words, setting modulePathIgnorePatterns
to ["/node_modules/"]
causes don'tMock() method to break mocking. This is true despite the fact that, according to the docs this is the default pattern.
I have confirmed this on the current version of jest on NPM, as well as the current HEAD commit (dbd9eb2). I have confirmed that setting modulePathIgnorePatterns
to something like `["/nonsense_path/"] makes everything work.
In addition, note that the issue is that setting modulePathIgnorePatterns
is causing calling dontMock()
to break mocking. These tests both pass:
describe('SomeTest', function() {
it("requires underscore (unmocked) and jQuery (mocked)", function() {
jest.dontMock('underscore');
var _ = require('underscore');
var $ = require('jquery');
expect(_.mock).toBeUndefined();
expect($.mock).toBeUndefined();
})
});
Showing that calling dontMock()
causes all future requires to be unmocked. As well as:
describe('SomeTest', function() {
it("requires underscore (unmocked) and jQuery (mocked)", function() {
var _ = require('underscore');
var $ = require('jquery');
expect(_.mock).toBeDefined();
expect($.mock).toBeDefined();
})
});
Showing that without dontMock()
, everything still works as expected. It's the combination of setting modulePathIgnorePatterns
, calling dontMock()
, and then trying to require something that should be mocked that's broken.
(I originally submitted the bug as #64, which I've closed because it turns out I was completely wrong about the actual issue.)
There seems to be an issue when using config.rootDir when mocking node_module(s).
test file:
'use strict';
describe('using config.rootDir', function() {
it('has problems when mocking node_modules', function() {
// lodash and kew have been installed with npm
jest.setMock('lodash', 'lodash');
jest.setMock('kew', 'kew');
console.log(require('lodash'));
console.log(require('kew'));
});
it('works when mocking my own modules', function() {
// ../foo and ../bar are my own modules
jest.setMock('../foo', 'foo');
jest.setMock('../bar', 'bar');
console.log(require('../foo'));
console.log(require('../bar'));
});
});
this yields:
Using Jest CLI v0.1.15
Found 1 matching tests...
PASS __tests__/baz-test.js (0.032s)
kew
kew
foo
bar
1 tests passed (1 total)
Run time: 0.86s
i was expecting:
Using Jest CLI v0.1.15
Found 1 matching tests...
PASS __tests__/baz-test.js (0.032s)
lodash
kew
foo
bar
1 tests passed (1 total)
Run time: 0.86s
Not sure if this is a Jest issue or a React issue. But, the following spec fails when using TestUtils.Simulate.mouseEnter. I will cross post in React repo issues list as well.
'use strict';
jest.autoMockOff();
describe('MouseEnter Test', function() {
var React, TestUtis,
Foo, foo;
beforeEach(function() {
React = require('react/addons');
TestUtils = React.addons.TestUtils;
Foo = React.createClass({
handleMouseEnter: function() {
console.log('i entered');
this.setState({ mouseEntered: true });
},
handleMouseOver: function() {
console.log('im over');
this.setState({ mouseOvered: true });
},
render: function() {
return React.DOM.div({
onMouseEnter: this.handleMouseEnter,
onMouseOver: this.handleMouseOver
});
}
});
foo = TestUtils.renderIntoDocument(Foo());
});
it('when mouseEnter simulated, should log to console and set state.mouseEntered to true', function() {
// this doesn't work
TestUtils.Simulate.mouseEnter(foo.getDOMNode());
expect(foo.state.mouseEntered).toBe(true);
});
it('when mouseOver simulated, should log to console and set state.mouseOvered to true', function() {
// this doesn't work
TestUtils.Simulate.mouseOver(foo.getDOMNode());
expect(foo.state.mouseOvered).toBe(true);
});
});
And, my console output:
Austins-MacBook-Pro:austin awei$ node ../bin/jest.js mouseover
Using Jest CLI v0.1.15
Found 1 matching tests...
FAIL __tests__/mouseover.spec.js (1.142s)
im over
● MouseEnter Test › it when mouseEnter simulated, should log to console and set state.mouseEntered to true
- TypeError: Cannot read property 'mouseEntered' of null
at Spec.<anonymous> (/Users/awei/work/jest/austin/__tests__/mouseover.spec.js:30:19)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
1 tests failed, 0 tests passed (1 total)
Run time: 2.215s
Hi,
I have a project with very specific SQL code that I need to test. I'm using node-postgres. It can be tested on jasmine-node via the done() callback, but I can't find any similar thing on jest.
I know that unit test are not supposed to hit the database and all that stuff, but I really need to test some big(ish) selects and updates.
Since this driver is always asynchronous, is there a way to do this with Jest ?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.