Explain Codes LogoExplain Codes Logo

What is the difference between 'it' and 'test' in Jest?

javascript
jest
bdd
testing
Anton ShumikhinbyAnton ShumikhinΒ·Aug 21, 2024
⚑TLDR

In Jest, it and test are aliases that define a test block. test is typically used for straightforward, action-based test descriptions, whereas it lends itself to behavior-oriented BDD style descriptions which read more like a sentence.

test('adds integers correctly', () => { // When Math does its job right expect(1 + 1).toBe(2); }); it('should add integers correctly', () => { // Trying to trick Math to fail 😈 expect(1 + 1).toBe(2); });

Make the choice of it or test based on your team’s terminology preference β€” their functionality is identical under the hood.

Understanding Aliases

Between it and test, there's more at play than just semantic: it's about turning your tests into informative narratives. it is typically used in behavior-driven development (BDD), where tests document the expected behavior of the unit under test.

// BDD style using `it` it('processes an API request', () => { // Test implementation }); // Action-based style using `test` test('processes an API request', () => { // Test implementation });

Decluttering your Test Suites

describe helps group related test cases, improving navigation and structure which becomes invaluable for reporting and maintenance.

describe('A bunch of mathematical operators', () => { it('successfully divides numbers', () => { // Dividing numbers, hopefully not by zero }); test('performs modulo operation', () => { // % is not for comments here }); });

Whether to use it or test within describe blocks depends purely on your test description style.

Dodging bullets with Test Exemptions

When you need to skip a test or focus on a specific one, Jest offers variations of it in the form of xit() and fit(). These features are surprisingly handy when you've got a flaky test on the loose!

// Dodging a test bullet for now xit('promises resolve eventually', () => { // I'll be back, promise! }); // Only this test has your undivided attention fit('promises sometimes reject', () => { // The promise was a lie. });

Of course, test.skip and test.only exist for test lovers.

Consistent Testing in Large Teams

When working in teams, having a common language is crucial. Therefore, decide as a team whether to use it or test β€” the decision could be influenced by factors such as existing test frameworks in use or the team's comfort level with the BDD style.

Introduce a linting rule to enforce the chosen style across your codebase. This ensures consistency in test descriptions, improves readability, and makes your code reviewer's life a whole lot easier.