Giter Club home page Giter Club logo

jest's Introduction

npm version Jest is released under the MIT license. Follow on Twitter

GitHub CI Status Coverage Status

Gitpod ready-to-code

Β 

πŸƒ Delightful JavaScript Testing

πŸ‘©πŸ»β€πŸ’» Developer Ready: A comprehensive JavaScript testing solution. Works out of the box for most JavaScript projects.

πŸƒπŸ½ Instant Feedback: Fast, interactive watch mode only runs test files related to changed files.

πŸ“Έ Snapshot Testing: Capture snapshots of large objects to simplify testing and to analyze how they change over time.

See more on jestjs.io

Table of Contents

Getting Started

Install Jest using yarn:

yarn add --dev jest

Or npm:

npm install --save-dev jest

Note: Jest documentation uses yarn commands, but npm will also work. You can compare yarn and npm commands in the yarn docs, here.

Let's get started by writing a test for a hypothetical function that adds two numbers. First, create a sum.js file:

function sum(a, b) {
  return a + b;
}
module.exports = sum;

Then, create a file named sum.test.js. This will contain our actual test:

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

Add the following section to your package.json:

{
  "scripts": {
    "test": "jest"
  }
}

Finally, run yarn test or npm test and Jest will print this message:

PASS  ./sum.test.js
βœ“ adds 1 + 2 to equal 3 (5ms)

You just successfully wrote your first test using Jest!

This test used expect and toBe to test that two values were exactly identical. To learn about the other things that Jest can test, see Using Matchers.

Running from command line

You can run Jest directly from the CLI (if it's globally available in your PATH, e.g. by yarn global add jest or npm install jest --global) with a variety of useful options.

Here's how to run Jest on files matching my-test, using config.json as a configuration file and display a native OS notification after the run:

jest my-test --notify --config=config.json

If you'd like to learn more about running jest through the command line, take a look at the Jest CLI Options page.

Additional Configuration

Generate a basic configuration file

Based on your project, Jest will ask you a few questions and will create a basic configuration file with a short description for each option:

yarn create jest

Using Babel

To use Babel, install required dependencies via yarn:

yarn add --dev babel-jest @babel/core @babel/preset-env

Configure Babel to target your current version of Node by creating a babel.config.js file in the root of your project:

// babel.config.js
module.exports = {
  presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};

The ideal configuration for Babel will depend on your project. See Babel's docs for more details.

Making your Babel config jest-aware

Jest will set process.env.NODE_ENV to 'test' if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g.

// babel.config.js
module.exports = api => {
  const isTest = api.env('test');
  // You can use isTest to determine what presets and plugins to use.

  return {
    // ...
  };
};

Note: 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:

// jest.config.js
module.exports = {
  transform: {},
};

Using webpack

Jest can be used in projects that use webpack to manage assets, styles, and compilation. webpack does offer some unique challenges over other tools. Refer to the webpack guide to get started.

Using Vite

Jest can be used in projects that use vite to serves source code over native ESM to provide some frontend tooling, vite is an opinionated tool and does offer some out-of-the box workflows. Jest is not fully supported by vite due to how the plugin system from vite works, but there is some working examples for first-class jest integration using the vite-jest, since this is not fully supported, you might as well read the limitation of the vite-jest. Refer to the vite guide to get started.

Using Parcel

Jest can be used in projects that use parcel-bundler to manage assets, styles, and compilation similar to webpack. Parcel requires zero configuration. Refer to the official docs to get started.

Using TypeScript

Jest supports TypeScript, via Babel. First, make sure you followed the instructions on using Babel above. Next, install the @babel/preset-typescript via yarn:

yarn add --dev @babel/preset-typescript

Then add @babel/preset-typescript to the list of presets in your babel.config.js.

// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', {targets: {node: 'current'}}],
+    '@babel/preset-typescript',
  ],
};

However, there are some caveats to using TypeScript with Babel. Because TypeScript support in Babel is purely transpilation, Jest will not type-check your tests as they are run. If you want that, you can use ts-jest instead, or just run the TypeScript compiler tsc separately (or as part of your build process).

Documentation

Learn more about using Jest on the official site!

Badge

Show the world you're using Jest β†’ tested with jest jest tested jest

[![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg?logo=jest)](https://github.com/jestjs/jest)
[![jest tested](https://img.shields.io/badge/Jest-tested-eee.svg?logo=jest&labelColor=99424f)](https://github.com/jestjs/jest)
[![jest](https://jestjs.io/img/jest-badge.svg)](https://github.com/jestjs/jest)

Contributing

Development of Jest happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving Jest.

Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated.

Read our contributing guide to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Jest.

To help you get your feet wet and get you familiar with our contribution process, we have a list of good first issues that contain bugs which have a relatively limited scope. This is a great place to get started.

Credits

This project exists thanks to all the people who contribute.

Thank you to all our backers! πŸ™

Support this project by becoming a sponsor. Your logo will show up here with a link to your website.

License

Jest is MIT licensed.

Copyright

Copyright Contributors to the Jest project.

jest's People

Contributors

aaronabramov avatar ahnpnl avatar amasad avatar biki-das avatar connormiha avatar cpojer avatar dependabot[bot] avatar dmitrysoshnikov avatar ericnakagawa avatar g-rath avatar gaearon avatar hramos avatar jeffmo avatar jeysal avatar kentaromiura avatar leebyron avatar mattphillips avatar mjesun avatar mrazauskas avatar orta avatar pedrottimark avatar renovate[bot] avatar rickhanlonii avatar rogeliog avatar rubennorte avatar scotthovestadt avatar simenb avatar thymikee avatar wtgtybhertgeghgtwtg avatar zpao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jest's Issues

jest.autoMockOff() bug with config.rootDir

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.

emfile issues when running jest/npm test command

> [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)

Environment file doesn't have access to `jest` object

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.

can't test condition for non-existed key in object

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!

Explicitly setting modulePathIgnorePatterns to the default value breaks dontMock method

Steps to repo:

  1. Create a new folder
  2. Run npm install jquery underscore jest-cli
  3. Run npm init and accept all defaults except setting the test command to jest
  4. Place this following test into __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.)

Mocking Backbone throws an error

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)

Error reading file

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.

when using the config.rootDir jest.setMock doing something unexpected.

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

Jest Installation Error

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
(```

'use strict' declaration doesn't seem to do anything

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

Require'ing a json file twice returns undefined

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).

Using dontMock() disables all mocking

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.

TypeError: Object [object global] has no method 'getSelection'

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.

it statements dramatically increase test runtime

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

Support for RequireJS

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?

Contextify breaks with scripts starting with #!

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).

Unused (non-Jest) test files in npm packages break Haste

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.

Async tests

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 ?

Syntax error when require-ing non-JavaScript files

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.

Without a preprocessor

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)

With a React preprocessor

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

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.

Using 'dontMock()' on a npm-module disables mocking for all npm-modules.

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.

when using the config.rootDir jest.setMock doing something unexpected.

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

Requiring coffee files without an extension is broken

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:

  1. create examples/coffeescript/common.coffee. It can be an empty file, it just should exist.
  2. replace sum.coffee with the code below.
  3. coffee sum.coffee and see that you get get the output 11
  4. run npm test. It will throw the Cannot find module error.

examples/coffeescript/sum.coffee

# 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)

React Tutorial tests not running

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...

TestUtils.Simulate.mouseEnter not working as expected

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

A `dontMock` for unmocking a whole dependency tree?

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?

Browserify's browser directives in package.json are ignored

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:

  • Jest uses the wrong entry point (the one for node instead of browserify)
  • Even if that's corrected, the browserify version will fail when require'ing 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.

Document ulimit setting/troubleshooting on the getting started doc

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.

"cannot read property ref of null" error when module.exports === undefined

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.

'require' can resolve to bad module version from other dependencies

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:

  1. jest-cli needs the precise v1.2.4 of underscore, hence it gets its own underscore version in jest-cli/node_modules/underscore
  2. HasteModuleLoader 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.
  3. When backbone calls 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...

Support globally installed modules

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.

Glob style file patterns instead of regular expressions?

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>)

Doesn't work with Ionic Framework out of box

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"
    ]
}

Use jasmine's `toHaveBeenCalled` rather than `toBeCalled`

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

Tests crash when requiring React Addons

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

jest -o crashes

$ 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...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.