Nwb: Add Jest support

Created on 6 Sep 2016  ยท  30Comments  ยท  Source: insin/nwb

Jest got _good_

Thinking this should be added as a question when creating an app.

enhancement help wanted

Most helpful comment

In case this helps someone else landing here, here's how I got it to work:

./jest.transform.js

module.exports = require('babel-jest').createTransformer({
  presets: ['es2015', 'react', 'stage-1'], // or whatever you need
});

"jest" entry in package.json:

"transform": {
  "^.+\\.js$": "<rootDir>/jest.transform.js"
}

All 30 comments

any progress on this?

No, as I don't need this right now, I just want to try it when I have time/motivation to do so.

PRs are welcome.

Do you want to include jest in nwb test --jest or move the dependency directly to the template and run tests via "test": "jest"?

For example:

__test__/App-test.js:

// Exclude css and svg from test
jest.mock('../src/react.svg', () => 'react-svg')
jest.mock('../src/App.css', () => 'app-css')

import renderer from 'react-test-renderer'
import React from 'react'
import App from '../src/App'

const renderedApp = renderer.create(<App />)

describe('Renders without errors', () => {
  it('Renders correctly', () => {
    expect(renderedApp.toJSON()).toMatchSnapshot()
  })
})

.babelrc:

{
  "presets": ["es2015", "react"]
}

And 4 more modules: jest, react-test-renderer, babel-preset-es2015 and babel-preset-react

For future reference, adding jest to a nwb app is straightforward. Check out this gist for a walkthrough.
I could add to docs until I or someone here has time to submit PR ?

Thanks for the research and examples @RakanNimer - my preferred approach (long-term) would be to turn both the current Karma/Mocha setup and Jest integration into testing plugins which follow the nwb approach of generating config (configurable via nwb.config.js) and calling the tools for you, passing the config.

We can then make testing a question when creating a new project, install the appropriate plugin and generate skeleton tests.

Last time I checked, the only thing which seemed to be missing to support this was that you couldn't pass Babel config directly to Jest, rather it had to be in a .babelrc file.

@insin Ran into that last issue you mentioned. Here is how you can do it.
https://gist.github.com/loklaan/3b4990f0f66a0103f34029829009e417
Very succinct example with hard imported babel presets, but you get the picture! ๐Ÿ˜„

You may also be able to use the transform option, but it's been awhile since I've touched this stuff... http://facebook.github.io/jest/docs/configuration.html#transform-object-string-string

@loklaan ooh, that looks good. Any hacking goes as long as it can stay under the hood.

In case this helps someone else landing here, here's how I got it to work:

./jest.transform.js

module.exports = require('babel-jest').createTransformer({
  presets: ['es2015', 'react', 'stage-1'], // or whatever you need
});

"jest" entry in package.json:

"transform": {
  "^.+\\.js$": "<rootDir>/jest.transform.js"
}

I'm keen to chip away at this one. Would be great to grab some scope from you.

So from the looks of it, the intended experience goes like:

  • User prompt at nwb init, to choose a testing framework (jest/karma)
  • nwb will know

    • what to install

    • what config to to put in nwb.config.js (if there would be any. ie karma plugins)

    • the files to scaffold for chosen framework

I think this would involve:

  1. Implementing a user prompt.
    I don't think there is currently one in any of the commands. _Got a module preference?_
  2. Pulling karma out into a plugin, and the same for jest.
  3. Deciding how to move forward with scaffolding.
    Do we want to have the karma/jest scaffold templates in nwb, or in the plugins?

@loklaan thanks for looking at this and the other stuff you're doing. I've made you a collaborator so you can have at it, as I'm at a bit of a low ebb time/motivation-wise at the moment.

  1. Inquirer is currently used in createProject.js for component/module projects.

  2. Fun. I guess this means needing to make a proper decision on plugin architecture. My initial implementation for CSS preprocessors assumed plugins would export an object with properties providing configuration for extension points nwb supports, so plugins don't have either responsibility or free reign to modify config.

  3. How about having a basic test scaffold which gets used unless the project type you're creating can provide a specific scaffold for the type of testing plugin you're using (details TBD)?

@insin Cheers!

Good to know where you're at motivation wise at the moment โ€“ I'll try not to drag you into stuff.

I've carved out time for this next week, but I could be testing ideas on the weekend too.

@loklaan update...

I used clauderic's method to get Jest working

configure package.json with:

    "test": "jest",
    "test:watch": "jest --watch",
    "coverage": "jest --coverage",
    "coverage:watch": "jest --coverage --watch"

one problem encountered is:

  • the jest.transform.js file is configured for minimal features. It does not support importing .css, .svg, etc.

@dearfrankg We'll resolve this by sharing the babel config with jest.

This coming Friday is devoted to getting Jest into nwb. ๐Ÿ’ฅ Should have something ready to test for the weekend.

@dearfrankg Just re-read your comment - sorry, you were referring to non-code files and I missed that. We'll do something internally, similar to the suggestion made on "Using Jest with Webpack" page.

Not this Friday, but Monday*

This worked for me :

.babelrc

{
  "presets": ["es2015", "react", "stage-0"],
  "plugins": ["transform-class-properties"]
}

package.json

"scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "coverage": "jest --coverage",
    "coverage:watch": "jest --coverage --watch",
},
"jest": {
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)(\\?.*)?$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(css|less)$": "identity-obj-proxy"
    }
  }

__mocks__/fileMock.js

module.exports = 'test-file-stub';

and i use it with storyshots :

shots.test.js

import initStoryshots from 'storyshots';
initStoryshots();

Now all refs, findDOMNode and such dont work...

Looking forward for Jest on nwb!

In the meantime, anyone has an example of how the setup with Jest would look like? Or a step by step on what to do, and why? I haven't done much with Jest before, a bit of this is going over my head.

It looks promising ๐Ÿ‘

@revolunet Adding a .babelrc does not work with some nwb use cases.

For example nwb build-react-component need to write a temporary .babelrc during build so the build crash if you have one.

This is what I did:

jest.transform.js

module.exports = require('babel-jest').createTransformer({
  presets: ["es2015", "react"],
  plugins: ["transform-object-rest-spread"],
});

jest.config.js

"transform": {
  "^.+\\.js$": "<rootDir>/jest.transform.js"
},

package.json

scripts": {
    "test": "jest --config jest.config.json --no-cache",
    "test:coverage": "npm test --coverage",
    "test:watch": "npm test --server",
}

Solution found here

jest.mock('../src/react.svg', () => 'react-svg')
jest.mock('../src/App.css', () => 'app-css')

@ntwcklng
It's can solve the problem,but I don't know what it meaning? and the docs told me to write the

"moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/spec/__mocks__/fileMock.js",
      "\\.(css|scss)$": "<rootDir>/spec/__mocks__/styleMock.js"
    }

in the package.json,but it's doesn't work ,but you code in the test file is work !! can you tell more about the meanning of your code ,THX

@baixiaoji jest.mock removes the specified files from the test pipeline. See: https://facebook.github.io/jest/docs/jest-object.html#jestmockmodulename-factory-options

@ntwcklng
why I write the moduleNameMapper config to stub out resources,but when I npm run test,it's err

  โ— Test suite failed to run

    C:\workFile\bigdream\ToLearn\selfapp\src\index.css:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.hovered{
                                                                                             ^

    SyntaxError: Unexpected token .

why it load the css file?

Install jest-css-modules

yarn add jest-css-modules --dev

Add it to your jest config:

  "moduleNameMapper": {
    "\\.(css)$": "<rootDir>/node_modules/jest-css-modules"
  }

It resolves css parsing problems for me

@xuopled
I add the jest-css-modules,then it err

 FAIL  .\Link.react.test.js
  โ— Test suite failed to run

    Cannot find module '../../package' from 'node.js'

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
      at Object.<anonymous> (node_modules/babel-core/lib/api/node.js:60:16)

Do you use special config for your jest?

I don't know what is the special config,but I add the

 "moduleNameMapper": {
    "\\.(css)$": "<rootDir>/spec/node_modules/jest-css-modules"
  }

then has the early err

 C:\workFile\bigdream\ToLearn\selfapp\src\index.css:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.hovered{
                                                                                             ^

    SyntaxError: Unexpected token .

Try to follow the documentation:
http://facebook.github.io/jest/docs/webpack.html

If you use css modules, maybe this issue can help you: https://github.com/facebook/jest/issues/1220

Hey @baixiaoji you should head over to the Reactiflux community for hands on help with Jest problems.

Everyone here has been very helpful so far, but it's not on-topic.

Cheers!

Hey just to let everyone know, I can no longer put time into implementing this issue (through #292).

I don't want this to come off negative to nwb, because it's actually great. So, to be open about the reason...

Awhile ago I started building ontop of nwb for an company-internal tool. It was around the time I picked up this issue to implement Jest as a plugin for nwb. The internal tool now encapsulates other tools, like storybook and jest. It's at a point now where I'm using nwb fill one gap: generating webpack configs. That part is a hack, and it's clearly not what nwb was solely made for. I'll be replacing it soon, which means I won't have any vested interest in nwb.

If anyone here would like to pick up the issue (I still think it would be very very cool for nwb), then reply in this thread or in #292. I could give some pointers, and insin can get some eyes on whos showing interest.

๐Ÿ‘ peace out

Was this page helpful?
0 / 5 - 0 ratings

Related issues

loklaan picture loklaan  ยท  3Comments

LeoDT picture LeoDT  ยท  5Comments

rudfoss picture rudfoss  ยท  4Comments

brumm picture brumm  ยท  6Comments

clayrisser picture clayrisser  ยท  3Comments