If you're just getting into testing your JavaScript or React Native app,
Jest is one of the easiest tools to start with. It's fast, simple, and
works beautifully with modern frameworks.
This tutorial will walk you through a minimal setup, a first
test, and what jest.setup.ts
is all about.
🧩 Step 1 --- Install Jest
If your project uses JavaScript:
npm install --save-dev jest
If you're using TypeScript:
npm install --save-dev jest ts-jest @types/jest
⚙️ Step 2 --- Add Jest to your scripts
Add this to your package.json
:
{
"scripts": {
"test": "jest"
}
}
Now you can run tests with:
npm test
🧪 Step 3 --- Write your first test
Create a simple function:
// sum.js
export function sum(a, b) {
return a + b;
}
Then create a test file called sum.test.js
:
// sum.test.js
import { sum } from './sum';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Now run npm test
and you'll see:
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3
That's it! You've written your first Jest test 🎉
🧠 Step 4 --- What is jest.setup.ts
?
When your app grows, you'll often need to prepare some global setup for
all tests --- like mocking fetch
, silencing warnings, or importing
custom matchers.
That's where jest.setup.ts
(or .js
) comes in.
It's a special file that runs before each test, letting you
configure Jest's environment once instead of repeating setup code
everywhere.
🧩 Example --- Simple jest.setup.ts
// jest.setup.ts
import '@testing-library/jest-native/extend-expect';
// Optional: silence React Native warnings
jest.spyOn(global.console, 'warn').mockImplementation(() => {});
Then tell Jest to use this setup file in your config:
// jest.config.js or jest.config.ts
export default {
preset: 'react-native', // or 'ts-jest' for TypeScript projects
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
};
Now this setup runs before all your tests --- perfect for initializing
testing libraries or mocking APIs.
🧠 When Do You Need jest.setup.ts
?
You can skip it for basic logic tests like the sum()
example. But
you'll find it essential once you test React components, hooks, or
APIs, where you might:
- Import
@testing-library/jest-native/extend-expect
- Mock
fetch
orAsyncStorage
- Initialize React Navigation mocks
- Silence React Native warnings
✅ Summary
Purpose File Example
Write basic tests *.test.js
sum.test.js
Preconfigure testing jest.setup.ts
global imports, mocks,
environment matchers
Tell Jest about setup jest.config.js
setupFilesAfterEnv
Top comments (0)