Skip to content

Instantly share code, notes, and snippets.

@hliyan
Last active November 25, 2022 13:10
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hliyan/c50bfe7d3a9d83216872d9b6271def8b to your computer and use it in GitHub Desktop.
Save hliyan/c50bfe7d3a9d83216872d9b6271def8b to your computer and use it in GitHub Desktop.
Jest with ES6 imports and React

Create project and install deps

mkdir hello
cd hello

npm init
...
test command: jest --coverage
...

npm install --save-dev jest babel-jest babel-preset-env babel-preset-react

For more info, see: https://facebook.github.io/jest/docs/en/getting-started.html

Setup ES6 and react

vi .babelrc
{
    "presets": ["env", "react"]
}

Create files as per jest getting started page

vi sum.js
const sum = (a, b) => {
  return a + b;
};
export default sum;
vi sum.test.js
import sum from './sum';

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

Running

jest

or,

npm test

Expected output

 PASS  ./sum.test.js
  ✓ adds 1+2 to equal 3 (2ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.565s, estimated 1s
Ran all test suites.
----------|----------|----------|----------|----------|----------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
----------|----------|----------|----------|----------|----------------|
All files |      100 |      100 |      100 |      100 |                |
 sum.js   |      100 |      100 |      100 |      100 |                |
----------|----------|----------|----------|----------|----------------|
@elalaouifaris
Copy link

For babel 7, we need to use @babel/preset-env instead of babel-preset-env.
Thanks for the notes. Helped me set testing with Jest in ES6.

@hliyan
Copy link
Author

hliyan commented Jul 17, 2019

Thanks for the tip. I'll make the change

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment