Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Babel Jest Not Being used. #770

Closed
AdamKyle opened this issue Mar 5, 2016 · 52 comments
Closed

Babel Jest Not Being used. #770

AdamKyle opened this issue Mar 5, 2016 · 52 comments

Comments

@AdamKyle
Copy link

AdamKyle commented Mar 5, 2016

Seems the Babel-Jest Project hasn't been touched in 4 months so Ill post this issue here.

Consider the following code:

var isClass = require('is-class');

export default () => {
  let _container = [];

  return {

    /**
     * Register the dependency under its own name.
     */
    register(name, dependency) {
      _container.push({name: name, dependency: dependency});
    },

    /**
     *
     */
    fetch(name) {
      var toy = _container.filter(function(container){
        return container.name === name;
      });

      console.log(toy);
    },

    get() {
      return _container;
    }
  }
}

Consider the following test:

jest.dontMock('../src/toy_box/toy_box.js');

import ToyBox from '../src/toy_box/toy_box.js';

describe('registrater dependency', () => {
  it ('should register a function to the container', () => {
    var foo = function() {};

    ToyBox.register('foo', foo);
    expect(ToyBox.container.length).toEqual(1);
  });
});

Now consider the following package.json:

{
  "name": "toy-box",
  "description": "Toy Box is a simple and efficient DI system based off symfony and other concepts.",
  "version": "0.0.1",
  "dependencies": {
    "babel": "^6.1.18",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-stage-0": "^6.1.18",
    "babelify": "7.2.0",
    "browserify": "12.0.1",
    "gulp": "3.9.0",
    "vinyl-source-stream": "1.1.0",
    "babel-plugin-lodash": "^1.0.1",
    "is-class": "0.0.4",
    "babel-runtime": "^6.2.0"
  },
  "devDependencies": {
    "babel-cli": "^6.6.5",
    "babel-core": "^6.2.1",
    "babel-jest": "^6.0.1",
    "babel-preset-es2015": "^6.6.0",
    "babel-template": "^6.2.0",
    "babel-traverse": "^6.2.0",
    "babel-types": "^6.2.0",
    "core-js": "^1.2.6",
    "filesaver.js": "0.2.0",
    "inherits": "^2.0.1",
    "isarray": "0.0.1",
    "jest-cli": "^0.8.2",
    "lodash": "^3.10.1",
    "rmmv-mrp-core": "0.0.14"
  },
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "scriptPreprocessor": "./node_modules/babel-jest",
    "testFileExtensions": [
      "es6",
      "js"
    ],
    "moduleFileExtensions": [
      "js",
      "json",
      "es6"
    ]
  }
}

And the .babel-rc

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

Finally the result from the test:

npm test

> [email protected] test /Users/AdamBalan/Documents/toy-box
> jest

Using Jest CLI v0.8.2, jasmine1
 FAIL  __tests__/toy_box-test.js 
● Runtime Error
SyntaxError: Unexpected token import
npm ERR! Test failed.  See above for more details.

Not sure how import is an unexpected token, also if you notice, babel-jest isnt being used in the compile step: Using Jest CLI v0.8.2, jasmine1

@cpojer
Copy link
Member

cpojer commented Mar 5, 2016

I literally just pushed an update that makes all of this better. I deprecated https://github.com/babel/babel-jest (and just pushed the README change, thanks for reminding me!) because it moved into this repository.

Update to 0.9.0 and babel-jest 9.0.0 and it should be good. Switch the dontMock to unmock too! The website received a huge update with all the new info: facebook.github.io/jest/ – please read the new Getting Started guide :)

@cpojer cpojer closed this as completed Mar 5, 2016
@AdamKyle
Copy link
Author

AdamKyle commented Mar 5, 2016

@cpojer I updated everything as per the new getting started docs but now when I run the tests, same code as above:

Using Jest CLI v0.9.0, jasmine2
 FAIL  __tests__/toy_box-test.js
● Runtime Error
SyntaxError: Unexpected token import
    at eval (native)
npm ERR! Test failed.  See above for more details.

How is import not a thing, also why isnt babel-jest being used?

@cpojer
Copy link
Member

cpojer commented Mar 5, 2016

babel-jest is auto-detected now and 9.0 is on npm: https://www.npmjs.com/package/babel-jest

I'm unsure what's going on. Can you paste your jest config from your package.json file? If you clone the jest repository and go into examples/react ( https://github.com/facebook/jest/tree/master/examples/react ) you can see how it is supposed to work. babel-jest and jest-cli are installed alongside each other, and as long as babel-jest can be resolved from your rootDir, it should get auto-detected and will work properly.

@ms88privat
Copy link

@cpojer I have kinda the same problem. Trying to write unit tests for react native.

I use this script in package.json
http://facebook.github.io/react-native/docs/testing.html#content

My test test case:

// jest.unmock('../cool');
jest.autoMockOff();

import add from '../cool';
// import {sub} from '../cool';

describe('Cool', () => {
  it('cool test', () => {
    console.log('add', add); // console.log('sub', sub);
    const resp = add(2, 3);
    expect(resp).toBe(5);
  });
});

cool.js:

export default function add(a, b) {
  return a+b;
}
export function sub(a, b) {
  return a-b;
}

console output:

Using Jest CLI v0.9.0, jasmine2
Running 1 test suite...add function add() {return mockConstructor.apply(this,arguments);}
 FAIL  src/logic/__tests__/cool-test.js (2.74s)
● Cool › it cool test
  - Expected: undefined toBe: 5
        at stack (eval at runSourceText (node_modules/jest-cli/src/environments/JSDOMEnvironment.js:36:24), <anonymous>:1484:17)
1 test failed, 0 tests passed (1 total in 1 test suite, run time 5.682s)
npm ERR! Test failed.  See above for more details.

I don't understand why the function gets mocked? (unmock doesn't work too)

When I uncomment and try to import {sub}, I got a different error:

Using Jest CLI v0.9.0, jasmine2
 FAIL  src/logic/__tests__/cool-test.js (2.747s)
● Cool › it cool test
  - ReferenceError: _cool is not defined
        at Object.eval (eval at runSourceText (node_modules/jest-cli/src/environments/JSDOMEnvironment.js:36:24), <anonymous>:9:34)
1 test failed, 0 tests passed (1 total in 1 test suite, run time 5.717s)
npm ERR! Test failed.  See above for more details.

I also got SyntaxError: Unexpected token import, but I did not remember what I did there.

Thanks for your work and I'm looking forward for more React-Native integration 👍

@cpojer
Copy link
Member

cpojer commented Mar 5, 2016

@AdamKyle would you mind posting your updated package.json?

@ms88privat would you mind also pasting your package.json? Your directory structure would also be good to know, for example, where is your .babelrc (and what is in it) and what does require.resolve('babel-jest') give you from the root of your project?

Also, please remove scriptPreprocessor from your setup, if you are using babel-jest 9.0.

Please make sure you are using babel-jest 9.0.0. Before this version, unmock will not work properly. This was published just a few hours ago (right around when this issue was created :) ).

I'm also planning to update the docs on react-native testing soon. @ms88privat thanks for linking that page, I wasn't aware that react-native had their own page on testing, which is now outdated with jest 0.9.0 :)

@ms88privat
Copy link

@cpojer At the moment I don't have a .babelrc file, because it wasn't necessary (raised errors) since the Babel5 React Native upgrade. But I did try the version like @AdamKyle, but it didn't change anything.

I started this project yesterday completely from the ground up (with react-native init app), thats why all my dependencies are up2date.

I put require.resolve('babel-jest') in my index.ios.js file and it raised the error require.resolve is not a function

package.json:

{
  "name": "app",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "jest": {
    "scriptPreprocessor": "node_modules/react-native/jestSupport/preprocessor.js",
    "setupEnvScriptFile": "node_modules/react-native/jestSupport/env.js",
    "testPathIgnorePatterns": [
      "/node_modules/",
      "packager/react-packager/src/Activity/"
    ],
    "testFileExtensions": [
      "js"
    ],
    "unmockedModulePathPatterns": [
      "promise",
      "source-map"
    ]
  },
  "dependencies": {
    "lodash": "^4.6.1",
    "normalizr": "^2.0.0",
    "react-native": "^0.21.0",
    "react-native-router-flux": "^2.3.10",
    "react-native-vector-icons": "^1.3.2",
    "react-redux": "^4.4.0",
    "redux": "^3.3.1",
    "redux-diff-logger": "0.0.9",
    "redux-logger": "^2.6.1",
    "redux-saga": "^0.9.3",
    "reselect": "^2.1.0"
  },
  "devDependencies": {
    "babel-jest": "^9.0.0",
    "eslint": "^2.3.0",
    "eslint-config-standard": "^5.1.0",
    "eslint-config-standard-react": "^2.3.0",
    "eslint-plugin-promise": "^1.1.0",
    "eslint-plugin-react": "^4.1.0",
    "eslint-plugin-react-native": "^1.0.0",
    "eslint-plugin-standard": "^1.3.2",
    "jest-cli": "^0.9.0"
  }
}

I also had more babel dev dependencies installed (like babel-polyfill), but they didn't change a thing and so I had removed them again.

EDIT: my folder structure: https://db.tt/iwUIjIeu

Looking forward for your step by step guide with a fresh react-native project :)

@cpojer
Copy link
Member

cpojer commented Mar 6, 2016

You have a custom setup for scriptPreprocessor which will overwrite babel-jest. My recommendation is to follow the babel-jest setup guide in the Getting Started section: https://facebook.github.io/jest/docs/getting-started.html#babel-integration

After you are done, I recommend installing the react-native preset: npm install --save-dev babel-preset-react-native and adding it to your .babelrc. This should be enough to make Jest work. As said, I will add documentation for this when I get to work next week – so there'll be more info on this for react-native specifically soon.

If you, for some reason, don't want to go through this, then you cannot use jest.unmock together with import statements. Your test files will then have to use require instead:

jest.unmock('Foo');

const Foo = require('Foo');

The reason this is, is because babel-jest 9.0.0 brings in the babel-plugin-jest-unmock with it that hoists unmock calls before imports. Without this, an import is run before an unmock call and is therefore not mocked.

Yet another solution, if you are using Jest 0.9.0 and you don't want to use automocking, you can set automock to off in the config. However, I haven't tried that on react-native yet.

Is that helpful for now? As said, there'll be more documentation soon.

@AdamKyle
Copy link
Author

AdamKyle commented Mar 6, 2016

This is long been solved, apologies for not getting back to it. In another of my issues you saw the toy box package.json, thats why my json file looks like now and everything as we have both seen works :)

@ms88privat
Copy link

@cpojer Thanks! It is working now.

Wrap-up for other people who want to use it with react-native:

  • I did not need the .babelrc file (and no babel-preset-react-native)

package.json:

{
  "name": "App",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "jest": {
    "testPathIgnorePatterns": [
      "/node_modules/",
      "packager/react-packager/src/Activity/"
    ],
    "testFileExtensions": [
      "js"
    ],
    "unmockedModulePathPatterns": [
      "promise",
      "source-map"
    ]
  },
  "dependencies": {
    "react-native": "^0.21.0"
  },
  "devDependencies": {
    "babel-jest": "^9.0.0",
    "babel-polyfill": "^6.6.1",
    "jest-cli": "^0.9.0"
  }
}

@ms88privat
Copy link

@cpojer I got another problem or maybe I misunderstand some concepts here (new to unit tests...)

If I importsomething in the file, which I'm going to test, It will raise this error:

Using Jest CLI v0.9.0, jasmine2, babel-jest
 FAIL  src/logic/__tests__/saga-test.js
● Runtime Error
SyntaxError: Unexpected token export
    at eval (native)
npm ERR! Test failed.  See above for more details.

Files to test:
(working)

export const TEST = 'TEST' 

(not working)

import x from 'x'
export const TEST = 'TEST'; 

Edit: The same happens with the .babelrc and react-native preset.

@cpojer
Copy link
Member

cpojer commented Mar 6, 2016

The react example ( https://github.com/facebook/jest/tree/master/examples/react ) I mentioned earlier does this with the correct setup and it works. I'm afraid I can't help you unless you push a repro somewhere on github that I can take a look at. I'm pretty sure this is some sort of configuration issue on your part.

@cpojer
Copy link
Member

cpojer commented Mar 6, 2016

Oh, I think I know why this has happened: Jest uses caching, and when you added a .babelrc, it wasn't recognized. Can you try again adding a .babelrcfile with the es2015 preset and running Jest with --no-cache once? That should make sure that config changes are properly picked up :) Without the es2015 preset, import/export will definitely not work.

@ms88privat
Copy link

@cpojer I'm not sure what I'm doing wrong, I installed .babelrc again with the presets and --no-cache, but it didn't solve my problem :(

import/export is working unless I have another import statement in the file I imported for testing:

test file in src/logic/__tests__:

// cool-test.js
jest.unmock('../cool');
import TEST from '../cool';

describe ...

is working with:

// src/logic/cool.js
export default 'TEST';

not working with:

// src/logic/cool.js
import something from 'something';
export default 'TEST';

Thanks for your patience with me... If you want to try it out, you could install a new react-native project with react-native init app and try my folder structure above.

@ms88privat
Copy link

@cpojer
Copy link
Member

cpojer commented Mar 6, 2016

thank you. That was very useful. The problem was that react-native was required but it wasn't being processed by babel-jest. I actually was unaware that we aren't shipping a compiled version of react-native on npm. You can update babel-jest to 9.0.1 and it should work properly. Thanks for creating a repro, that was great!

ghost pushed a commit that referenced this issue Mar 6, 2016
Summary:This changes it so react-native always gets compiled properly.

I thought long and hard about whether there should be an explicit whitelist, and yeah, probably there should be, but I don't want to overcomplicate things for now. One of the goals of Jest is to simplify the setup process, especially around Facebook's open source projects, and this helps greatly. New documentation for react-native testing is coming probably tomorrow.

see #770.
Closes #774

Differential Revision: D3017346

fb-gh-sync-id: e0c1444ce7c247fa3187ae024b38c81d19035f54
shipit-source-id: e0c1444ce7c247fa3187ae024b38c81d19035f54
@nitsujri
Copy link

nitsujri commented Mar 9, 2016

@cpojer thanks for the quick turn around against @ms88privat problem, I downloaded her repo and upgraded babel-jest to be 9.0.2 but I get a:

Using Jest CLI v0.9.1, jasmine2, babel-jest
 FAIL  src/__tests__/cool-test.js
● Runtime Error
TypeError: CallbackQueue.getPooled is not a function

Is there something else that I may be missing?

edit: sorry if ms88privat is not female.

@cpojer
Copy link
Member

cpojer commented Mar 9, 2016

@nitsujri hey! Not sure if you are using react-native or react, but whichever one you are using needs to be part of your unmockedModulePathPatterns or you need to call jest.unmock('react-native') before importing it.

Sorry, I still didn't have enough time to polish up the docs for react-native :)

@nitsujri
Copy link

@cpojer yep on native, so that was it! thanks!

@nitsujri
Copy link

@cpojer +1 for those would-be-uber-helpful docs.

Ran into a super basic Cannot find module 'Text' from 'react-native.js' and could not get past it. I think the docs/examples would officially nip this.

Not asking for help, just req the docs 👍. We're totally cool waiting a few days for them.

Thanks for all the awesomeness from Singapore.

@cpojer
Copy link
Member

cpojer commented Mar 10, 2016

Yep, working on it as hard as I can! :)

@logicalicy
Copy link

Apologies if I've overlooked the answer but was there a solution to this @nitsujri?

Ran into a super basic Cannot find module 'Text' from 'react-native.js' and could not get past it.

I've hit the same issue and couldn't discern from reading the conversation whether there was a straight forward fix?

I have a React Native project with following package.json:

{
  "name": "example_project",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node_modules/react-native/packager/packager.sh",
    "test": "jest --no-cache --verbose"
  },
  "dependencies": {
    "react": "^0.14.8",
    "react-native": "^0.22.2",
    "react-redux": "^4.4.0",
    "redux": "^3.3.1",
    "redux-thunk": "^1.0.3"
  },
  "devDependencies": {
    "babel-jest": "^9.0.3",
    "babel-polyfill": "^6.7.4",
    "jest-cli": "^0.9.2",
    "react-addons-test-utils": "^0.14.7"
  },
  "babel": {
    "presets": [
      "react-native"
    ]
  },
  "jest": {
    "globals": {
      "__DEV__": true
    },
    "testFileExtensions": [
      "js"
    ],
    "moduleFileExtensions": [
      "js"
    ],
    "testPathIgnorePatterns": [
      "/node_modules/",
      "packager/react-packager/src/Activity/"
    ],
    "unmockedModulePathPatterns": [
      "lodash",
      "promise",
      "source-map",
      "<rootDir>/node_modules/react-native/",
      "<rootDir>/node_modules/react-addons-test-utils"
    ]
  }
}

@nitsujri
Copy link

@logicalicy sadly not yet, I'm excitedly waiting for docs the from @cpojer.

@cpojer
Copy link
Member

cpojer commented Mar 31, 2016

The fix is probably going to look something like this as part of the "jest" config in package.json:

  "haste": {
      "defaultPlatform": "ios",
      "platforms": [
        "ios",
        "android"
      ],
      "providesModuleNodeModules": [
        "react-native"
      ]
    }

It may not work with 0.10.0 yet, but there will be point releases in which I'll make it work soon.

@qpowell
Copy link

qpowell commented Apr 26, 2016

@cpojer I followed what you mentioned above and notice that the jest setup is similar in the f8app repo. It fixes my TypeError: CallbackQueue.getPooled is not a function but now I just get TypeError: Cannot read property 'process' of undefined at setUpProcessEnv (/<my_project_dir>/node_modules/react-native/Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js:180:22)

Any word on when this will be covered in the docs? Just noticed that the last post in this thread was almost a month ago and wondering if I should just skip trying to get these tests working in the meantime.

Edit: Using Jest CLI v11.0.2, jasmine2, babel-jest

@AdrienLemaire
Copy link

Also stuck on this issue with Cannot find module 'View' from 'react-native.js', and trying the haste config didn't solve it either. @cpojer can you give a status update regarding the doc?

@kevinSuttle
Copy link

kevinSuttle commented Jul 28, 2016

I have this same issue with jest-cli 14.0.

import React from 'react';
    ^^^^^^
    SyntaxError: Unexpected token import

package.json:

  "jest": {
    "automock": false,
    "moduleFileExtensions": ["js", "jsx"],
    "moduleDirectories": ["node_modules"],
    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/react/",
      "<rootDir>/node_modules/react-dom/"
    ]
  }

.babelrc

{
  "presets": [
    "es2015",
    "stage-1",
    "react"
  ],
  "plugins": [
    "transform-runtime"
  ]
}
$ node -v
v6.2.2

How is babel-jest installed in such a way that it doesn't have to be mentioned in any config?

Edit

I added require('babel-polyfill'), which is only mentioned as a dependency here, though react-addons-test-utils is imported but not listed as a dependency. However, running through the tutorial gets the tests to pass now, but there is an odd warning.

❯ npm run jest --no-cache -s
Using Jest CLI v14.0.0, jasmine2, babel-jest
 PASS  __tests__/sum-test.js (0.271s)
Running 1 test suite...Warning: ReactComponentTreeDevtool: Missing React element for debugID 2 when building stack
Warning: ReactComponentTreeDevtool: Missing React element for debugID 2 when building stack
Warning: ReactComponentTreeDevtool: Missing React element for debugID 2 when building stack
Warning: ReactComponentTreeDevtool: Missing React element for debugID 2 when building stack
 PASS  __tests__/CheckboxWithLabel-test.js (0.778s)
2 tests passed (2 total in 2 test suites, run time 1.9s)

Double edit

npm install --save [email protected] fixes that 2nd error

@amir20
Copy link

amir20 commented Aug 17, 2016

I was able to identify the problem. It was related to

{
  "presets": [
    "react",
    [
      "es2015",
      {
        "loose": true,
        "modules": false
      }
    ]
  ]
}

I have to figure out how to fix that for production while Jest still work.

@brennancheung
Copy link

brennancheung commented Dec 5, 2016

I just ran into this same issue. I fixed it another way. The parsing error I was running into was on module related stuff like import and export.

Turns out I had disabled modules in my .babelrc in order to get tree shaking to work in webpack2.

"presets":  [
  ["es2015", {"modules": false}]
]

To work around it, I added a test specific env setting in my .babelrc to disable it.

"env": {
  "test": {
    "presets": [
      "es2015"
    ]
  }
}

I didn't need to use transform-es2015-modules-commonjs.

@VasilyShelkov
Copy link

I'm having a problem possibly related to this where I can't destructure exports from a file that has:

export const x = () => (...)

export default connect(...)(x)

in the test when I'm

import { x } from './someFile'
console.log(x)

x is undefined where as if I do:

import * as xFile from './someFile'
console.log(xFile.x)

it works correctly.

Any ideas ?

My .babelrc is:

{
  "presets": [["es2015", { "modules": false }], "react", "stage-0"],
  "env": {
    "test": {
      "presets": ["es2015", "react", "stage-0"]
    }
  },
  "plugins": ["transform-do-expressions"]                      
}                                                                   

I have installed babel-jest, babel-polyfill, jest etc...
Jest tests run just not when I try to destructure the export, it is undefined then.

Appreciate any help or suggestions, can provide more details

@CodinCat
Copy link
Contributor

CodinCat commented Dec 30, 2016

Same problem here.., my babelrc is exactly the same

{
  "presets": ["es2015", "react", "stage-0"],
  "plugins": [
    "react-hot-loader/babel"
  ]
}

and I've installed everything mentioned in docs

"devDependencies": {
  "babel-jest": "^18.0.0",
  "babel-polyfill": "^6.20.0",
  "jest": "^18.1.0"
},

tried every solution in this thread (install transform-es2015-modules-commonjs plugin, --no-cache, ...), just keep getting this error Unexpected token import, still don't know how to solve it.


I just tried mocha, with mocha --require babel-register and it works without any other configuration. Not sure why jest doesn't work.

@capaj
Copy link
Contributor

capaj commented Jan 24, 2017

I also have this issue. It's very mind boggling, because I have setup 2 repos and while first one works, second does not.

@joshjung
Copy link

joshjung commented Jan 26, 2017

Same issue right now and exact configuration as @CodinCat , I'll post if I find a solution.

UPDATE: Did the following and it started working:

  • npm unlink .
  • rm -rf node_modules
  • npm i
  • npm link .

It appears unlinking the current folder and reinstalling node_modules got it working again.

@verekia
Copy link

verekia commented Feb 10, 2017

I was having a similar issue when I realized I had an ignore field in my Babel config to avoid building **/*.test.js files. Turns out it also prevents babel-jest from doing its job on these files, which is why it seemed like it was not working at all.

@utexasdelirium
Copy link

This issue is frustrating as I think its a environment specific issue. 2 machines, 1 is affected by this and the other is not. On the affected machine, I've been trying to completely remove node and reinstall but the issue not going away.

@JMStudiosJoe
Copy link

JMStudiosJoe commented Mar 10, 2017

Having this error over and over, very annoying. Here is my output from running jest --debug running with --no-cache does nothing
.babelrc
{
"presets": [ "es2015", "react" , "stage-0" ]

}
output:
jest version = 19.0.2
test framework = jasmine2
config = {
"automock": false,
"bail": false,
"browser": false,
"cacheDirectory": "/var/folders/ys/5rpt8yjj6cj8h2bw2mvyps2m0000gn/T/jest",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"coverageReporters": [
"json",
"text",
"lcov",
"clover"
],
"expand": false,
"globals": {},
"haste": {
"providesModuleNodeModules": []
},
"moduleDirectories": [
"node_modules"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"moduleNameMapper": {},
"modulePathIgnorePatterns": [],
"noStackTrace": false,
"notify": false,
"preset": null,
"resetMocks": false,
"resetModules": false,
"roots": [
"/Users/joseph/Documents/WebDevWorkspace/mvp_frontend"
],
"snapshotSerializers": [],
"testEnvironment": "jest-environment-jsdom",
"testMatch": [],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testRegex": "/react/tests/.\.(ts|tsx|js)$",
"testResultsProcessor": null,
"testURL": "about:blank",
"timers": "real",
"transformIgnorePatterns": [
"react/src/swagger/
.js"
],
"useStderr": false,
"verbose": null,
"watch": false,
"transform": [
[
".*",
"/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/preprocessor.js"
]
],
"rootDir": "/Users/joseph/Documents/WebDevWorkspace/mvp_frontend",
"name": "8242ca72feef5a16444e1e1f89ae9235",
"setupFiles": [],
"testRunner": "/Users/joseph/.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-jasmine2/build/index.js",
"cache": true,
"watchman": true
}
FAIL react/tests/test_catalogs_component.tsx
● Test suite failed to run

/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/react/src/swagger/backend.js:10
import request from 'request';
^^^^^^
SyntaxError: Unexpected token import

  at e (../../../.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-runtime/build/transform.js:320:12)
  at Object.<anonymous> (react/src/services/backend.ts:3:20)
  at Object.<anonymous> (react/src/actions/catalog_actions.ts:3:17)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.09s
Ran all test suites.

package.json with current transformIgnorePatterns
"jest": {
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transformIgnorePatterns": [
"react/src/swagger/.js"
],
"transform": {".
": "./preprocessor.js"},
"testRegex": "/react/tests/.*\.(ts|tsx|js)$"
}

package.json with node_modules ignored
different error output:
jest version = 19.0.2
test framework = jasmine2
config = {
"automock": false,
"bail": false,
"browser": false,
"cacheDirectory": "/var/folders/ys/5rpt8yjj6cj8h2bw2mvyps2m0000gn/T/jest",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"coverageReporters": [
"json",
"text",
"lcov",
"clover"
],
"expand": false,
"globals": {},
"haste": {
"providesModuleNodeModules": []
},
"moduleDirectories": [
"node_modules"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"moduleNameMapper": {},
"modulePathIgnorePatterns": [],
"noStackTrace": false,
"notify": false,
"preset": null,
"resetMocks": false,
"resetModules": false,
"roots": [
"/Users/joseph/Documents/WebDevWorkspace/mvp_frontend"
],
"snapshotSerializers": [],
"testEnvironment": "jest-environment-jsdom",
"testMatch": [],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testRegex": "/react/tests/.\.(ts|tsx|js)$",
"testResultsProcessor": null,
"testURL": "about:blank",
"timers": "real",
"transformIgnorePatterns": [
"node_modules/(?!react)"
],
"useStderr": false,
"verbose": null,
"watch": false,
"transform": [
[
".
",
"/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/preprocessor.js"
]
],
"rootDir": "/Users/joseph/Documents/WebDevWorkspace/mvp_frontend",
"name": "8242ca72feef5a16444e1e1f89ae9235",
"setupFiles": [],
"testRunner": "/Users/joseph/.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-jasmine2/build/index.js",
"cache": true,
"watchman": true
}
FAIL react/tests/test_catalogs_component.tsx
● Test suite failed to run

/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/react/__tests__/test_catalogs_component.tsx:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){require('ts-jest').install();import React from 'react';
                                                                                                                      ^^^^^^
SyntaxError: Unexpected token import

  at e (../../../.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-runtime/build/transform.js:320:12)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.893s
Ran all test suites.

Any ideas and help would be appreciated, sorry can't provide github link since private repo but we are currently moving from angular typescript to react typescript. Thank you in advance.

@jamedranoa
Copy link

jamedranoa commented Mar 10, 2017

@JMStudiosJoe I think it might be because you modified the transform config see second note so babel-jest wont load

@JMStudiosJoe
Copy link

@jamedranoa can you provide a better example for the transform option, since I have tried many different combinations now and even the one the compiler was saying to use does not work.

@jamedranoa
Copy link

@JMStudiosJoe May I ask how your preprocessor file looks like? this might help #1466

@JMStudiosJoe
Copy link

@jamedranoa thank you for fast responses first of all, and my transform option is now working
"transform": {
".(ts|tsx)": "/node_modules/ts-jest/preprocessor.js"
},
with my ts file and not complaining about the import statement in my test... BUT it is now complaining about another import in my auto generated swagger js
react/tests/test_catalogs_component.ts
● Test suite failed to run

/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/react/src/swagger/backend.js:10
import request from 'request';
^^^^^^
SyntaxError: Unexpected token import

  at e (../../../.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-runtime/build/transform.js:320:12)
  at Object.<anonymous> (react/src/services/backend.ts:3:22)
  at Object.<anonymous> (react/src/actions/catalog_actions.ts:3:19)

@jamedranoa
Copy link

@JMStudiosJoe ahh ok this might be related kulshekhar/ts-jest#121

@JMStudiosJoe
Copy link

@jamedranoa Looks like it and their fix seems to be working now for the import error but then get another error complaining about my .tsx syntax and rendering my html
FAIL react/tests/test_catalogs_component.ts
● Test suite failed to run

/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/react/src/views/BuyerCatalogDashboard/BuyerCatalogDashboard.tsx:36
        return (<div>
                ^
SyntaxError: Unexpected token <

  at e (node_modules/jest-runtime/build/transform.js:320:12)
  at Object.<anonymous> (react/__tests__/test_catalogs_component.ts:6:31)

Says line 36 when that is not true the line containing the return(<div is further down in the render method. Is this a babel translation issue and my tsx files not compiling to js properly?

@jamedranoa
Copy link

@JMStudiosJoe would you mind sharing your current jest config? do you have set "jsx": "react" on TS_CONFIG?

@JMStudiosJoe
Copy link

@jamedranoa my current tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "ES6",
"noImplicitAny": false,
"jsx": "react",
"sourceMap": true,
"moduleResolution": "node",
"allowJs": true,
"allowSyntheticDefaultImports": true
}
}

along with jest in package.json

"globals": {
"TS_CONFIG": {
"module": "commonjs"
}
}

@jamedranoa
Copy link

@JMStudiosJoe looks like when you specify __TS_CONFIG__ then jest-ts wont read your tsconfig.json file(see), try removing the __TS_CONFIG__ key from the configuration or specify the path to your tsconfig.json file in it.

@JMStudiosJoe
Copy link

JMStudiosJoe commented Mar 10, 2017

back to my favorite import error...

FAIL react/tests/test_catalogs_component.ts
● Test suite failed to run

/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/react/src/swagger/backend.js:10
import request from 'request';
^^^^^^
SyntaxError: Unexpected token import

  at e (../../../.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-runtime/build/transform.js:320:12)
  at Object.<anonymous> (react/src/services/backend.ts:3:20)
  at Object.<anonymous> (react/src/actions/catalog_actions.ts:3:17)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.641s

is this right file to be using for jest? at e (../../../.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-runtime/build/transform.js:320:12) ??

UPDATE: in package.json added
"globals": {
"_ TS_CONFIG _": "tsconfig.json"
}
and now getting the error

jest
FAIL react/tests/test_catalogs_component.ts
● Test suite failed to run

Your test suite must contain at least one test.

  at onResult (../../../.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-cli/build/TestRunner.js:192:18)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.915s
Ran all test suites.

I believe I have 2 tests in my test file contrary to what the error is saying

import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { createStore } from 'redux';
import { expect } from 'chai';
import { shallow } from 'enzyme';

import BuyerCatalogDashboard from '../src/views/BuyerCatalogDashboard/BuyerCatalogDashboard';
import catalogReducer from '../src/reducers/catalog_reducer';

describe('', () => {
it('renders joey', () => {
const store = createStore(catalogReducer);
const wrapper = shallow(BuyerCatalogDashboard);
expect(true);
// var renderer = TestUtils.createRenderer();
// renderer.render(BuyerCatalogDashboard, {}).toMatchSnapshot();
})
});
describe('Addition', () => {
it('knows that 2 and 2 make 4', () => {
// expect(2 + 2).toBe(4);
});
});

UPDATE AGAIN
changing my file to test_catalogs-component.test.ts made the test get recognized but then my favorite damn import error is still with me

jest
FAIL react/tests/test_catalogs_component.test.ts
● Test suite failed to run

/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/react/src/swagger/backend.js:10
import request from 'request';
^^^^^^
SyntaxError: Unexpected token import

  at e (../../../.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-runtime/build/transform.js:320:12)
  at Object.<anonymous> (react/src/services/backend.ts:3:20)
  at Object.<anonymous> (react/src/actions/catalog_actions.ts:3:17)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.925s

@jamedranoa
Copy link

@JMStudiosJoe What node version do you have, >4? try changing the target config to ES5 if that's the case. try copying all your compilerOptions and putting them directly on the __TS_CONFIG__ object, if none of that works try leaving the config only as

"__TS_CONFIG__": {
        "module": "commonjs",
        "jsx": "react"
}

@JMStudiosJoe
Copy link

@jamedranoa my node is 6.3.1 tsconfig is now looking like
"TS_CONFIG": {
"module": "commonjs",
"target": "ES6",
"noImplicitAny": false,
"jsx": "react",
"sourceMap": true,
"moduleResolution": "node",
"allowJs": true,
"allowSyntheticDefaultImports": true
}

and.... same error ran with --debug option this time here is output:

jest --debug
jest version = 19.0.2
test framework = jasmine2
config = {
"automock": false,
"bail": false,
"browser": false,
"cacheDirectory": "/var/folders/ys/5rpt8yjj6cj8h2bw2mvyps2m0000gn/T/jest",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"coverageReporters": [
"json",
"text",
"lcov",
"clover"
],
"expand": false,
"globals": {
"TS_CONFIG": {
"module": "commonjs",
"target": "ES6",
"noImplicitAny": false,
"jsx": "react",
"sourceMap": true,
"moduleResolution": "node",
"allowJs": true,
"allowSyntheticDefaultImports": true
}
},
"haste": {
"providesModuleNodeModules": []
},
"moduleDirectories": [
"node_modules"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"moduleNameMapper": {},
"modulePathIgnorePatterns": [],
"noStackTrace": false,
"notify": false,
"preset": null,
"resetMocks": false,
"resetModules": false,
"roots": [
"/Users/joseph/Documents/WebDevWorkspace/mvp_frontend"
],
"snapshotSerializers": [],
"testEnvironment": "jest-environment-jsdom",
"testMatch": [],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testRegex": "(/react/tests/.*|\.(test|spec))\.(ts|tsx|js)$",
"testResultsProcessor": null,
"testURL": "about:blank",
"timers": "real",
"transformIgnorePatterns": [
"/node_modules/"
],
"useStderr": false,
"verbose": null,
"watch": false,
"transform": [
[
".(ts|tsx)",
"/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/node_modules/ts-jest/preprocessor.js"
]
],
"unmockedModulePathPatterns": [
"node_modules/react/",
"node_modules/enzyme/"
],
"rootDir": "/Users/joseph/Documents/WebDevWorkspace/mvp_frontend",
"name": "8242ca72feef5a16444e1e1f89ae9235",
"setupFiles": [],
"testRunner": "/Users/joseph/.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-jasmine2/build/index.js",
"cache": true,
"watchman": true
}
FAIL react/tests/test_catalogs_component.test.ts
● Test suite failed to run

/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/react/src/swagger/backend.js:10
import request from 'request';
^^^^^^
SyntaxError: Unexpected token import

  at e (../../../.nvm/versions/node/v6.3.1/lib/node_modules/jest/node_modules/jest-runtime/build/transform.js:320:12)
  at Object.<anonymous> (react/src/services/backend.ts:3:22)
  at Object.<anonymous> (react/src/actions/catalog_actions.ts:3:19)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.749s
Ran all test suites.

@JMStudiosJoe
Copy link

JMStudiosJoe commented Mar 10, 2017

UPDATE from above
added
"transform": {
** "^.+\.js$": "/node_modules/babel-jest",**
".(ts|tsx|js)": "/node_modules/ts-jest/preprocessor.js"
}

and now getting new errors which is progress, IMO I felt that my previous import errors was a translation issue between ts and js and adding this transform seemed to help with the reading of import in js files but now getting a weird error in my test for trying to render my component

npm t -- --no-cache

[email protected] pretest /Users/joseph/Documents/WebDevWorkspace/mvp_frontend
npm run lint

[email protected] lint /Users/joseph/Documents/WebDevWorkspace/mvp_frontend
tslint -c tslint.json 'src/**/.{ts,tsx}' -e 'react/src/swagger/.{ts,js,d.ts}'

[email protected] test /Users/joseph/Documents/WebDevWorkspace/mvp_frontend
jest "--no-cache"

FAIL react/tests/test_catalogs_component.ts
● Test suite failed to run

/Users/joseph/Documents/WebDevWorkspace/mvp_frontend/react/__tests__/test_catalogs_component.ts:10
        const wrapper = enzyme_1.shallow(/>);, chai_1.expect(true));
                                         ^
SyntaxError: Invalid regular expression: missing /

  at e (node_modules/jest-runtime/build/transform.js:320:12)
  at process._tickCallback (internal/process/next_tick.js:103:7)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.18s
Ran all test suites.
npm ERR! Test failed. See above for more details.

code for test:

import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { createStore } from 'redux';
import { expect } from 'chai';
import { shallow } from 'enzyme';

import BuyerCatalogDashboard from '../src/views/BuyerCatalogDashboard/BuyerCatalogDashboard';
import catalogReducer from '../src/reducers/catalog_reducer';

describe('', () => {
it('renders joey', () => {
const store = createStore(catalogReducer);
const wrapper = shallow();
expect(true);
// var renderer = TestUtils.createRenderer();
// renderer.render(BuyerCatalogDashboard, {}).toMatchSnapshot();
})
});

@JMStudiosJoe
Copy link

@jamedranoa I think I got things to work, now to make sure I can write meaningful tests. here is my configuration
"jest": {
"transform": {
** "^.+\.js$": "/node_modules/babel-jest", pretty sure this fixed issues**
".(ts|tsx|js)": "/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/react/tests/.*|\.(test|spec))\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"unmockedModulePathPatterns": [
"node_modules/react/",
"node_modules/enzyme/"
],
"globals": {
"TS_CONFIG": "tsconfig.json"
}
}
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "ES6",
"noImplicitAny": false,
"jsx": "react",
"sourceMap": true,
"moduleResolution": "node",
"allowJs": true,
"allowSyntheticDefaultImports": true
}
}

and this is my currently working tests, not sure how meaningful they are but its not complaining (yet)

import * as React from 'react';
import TestUtils from 'react-addons-test-utils';
import { createStore } from 'redux';
import { expect } from 'chai';
import { shallow } from 'enzyme';

import BuyerCatalogDashboard from '../src/views/BuyerCatalogDashboard/BuyerCatalogDashboard';
import catalogReducer from '../src/reducers/catalog_reducer';
describe('', () => {
it('renders joey', () => {
const store = createStore(catalogReducer);
const element = React.createElement(BuyerCatalogDashboard, {store: store}, {});

    const wrapper = shallow(element);
    expect(true);
    // var renderer = TestUtils.createRenderer();
    // renderer.render(BuyerCatalogDashboard, {}).toMatchSnapshot();
})

});
describe('Addition', () => {
it('knows that 2 and 2 make 4', () => {
// expect(2 + 2).toBe(4);
});
});

@jamedranoa thanks again for all your help, found the transform solution from this repo
https://github.com/kulshekhar/ts-jest#known-limitations-for-ts-compiler-options

@kamranayub
Copy link

FWIW, my issue was simply that my setup framework script file name was "jest.config.js" in the root directory... and that's the automatic configuration filename for Jest 🤕 🥇 Moving and renaming it to setup.js fixed it.

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 13, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests