I am new to jest and want to test my react.js app. I am following a book, React.js Essentials for jest part.
Here is my test code, Button-test.js
jest.dontMock('../Button.react');
describe('Button component', function () {
it('calls handler function on click', function () {
var React = require('react');
var TestUtils = require('react-addons-test-utils');
var Button = require('../Button.react');
var handleClick = jest.genMockFunction();
var button = TestUtils.renderIntoDocument(
<Button handleClick={handleClick}/>
);
var buttonInstance =
TestUtils.findRenderedDOMComponentWithTag(button, 'button');
TestUtils.Simulate.click(buttonInstance);
expect(handleClick).toBeCalled();
var numberOfCallsMadeIntoMockFunction =
handleClick.mock.calls.length;
expect(numberOfCallsMadeIntoMockFunction).toBe(1);
});
});
Here is my package.json
{
"name": "snapterest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-jest": "^6.0.1",
"babelify": "^6.2.0",
"browserify": "^12.0.1",
"gulp": "^3.9.0",
"jest-cli": "^0.8.0",
"vinyl-source-stream": "^1.1.0"
},
"dependencies": {
"react": "^0.14.0-beta3",
"react-dom": "^0.14.0-beta3",
"snapkite-stream-client": "^1.0.3"
},
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"testFileExtensions": ["es6", "js"],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react"
]
}
}
The problem is, when I run npm test, it reports the following syntax error. I think babel-jest is installed, and I have no idea why the syntax error is still there. Are there anything else I need to do except installing babel-jest?
source/components/__tests__/Header-test.js
● Runtime Error
SyntaxError:
/snapterest/source/components/__tests__/Header-test.js: Unexpected token (11:6)
9 |
10 | var button = TestUtils.renderIntoDocument(
> 11 | <Button handleClick={handleClick}/>
| ^
12 | );
Node. js has supported async functions by default since version 7.6. 0, so (as you suspected) Babel is not needed for Jest to run tests using async functions.
You can use the CLI to run Jest (that is if it's globally available in your PATH, e.g. by using yarn global add jest or npm install jest --global) with a variety of useful options. You should configure Babel to target your current version of Node by creating a babel.
Jest ships with one transformer out of the box – babel-jest . It will load your project's Babel configuration and transform any file matching the /\.
are you using babelify v7? if so, you may have followed the fix mentioned here that adds the react preset in your gulpfile. The same thing needs to happen with the test, but since this is run separately you can add this to a .babelrc file in root of your project:
{
"presets": ["react"]
}
npm test should then work correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With