GYLD
← All posts

3 July 2024

Mastering Modern Web Development Tools: Automated Testing with Jest and Cypress

#Automated Testing · #Jest · #Cypress · #Web Development · #JavaScript · #React

Mastering Modern Web Development Tools: Automated Testing with Jest and Cypress

Welcome back to our blog series on mastering modern web development tools. In this post, we’ll explore automated testing with Jest and Cypress. Testing is a crucial aspect of web development, ensuring that our applications work as expected and are free of bugs. Let’s dive into the importance of testing, how to get started with Jest and Cypress, and some best practices to follow.


The Importance of Testing in Web Development


Automated testing helps us catch bugs early, ensure code quality, and maintain a stable codebase. By writing tests, we can verify that our code behaves as expected, and we can refactor with confidence knowing that our tests will catch any regressions. Here at The Gyld, we believe that a robust testing strategy is essential for delivering high-quality software.


Getting Started with Jest for Unit Testing


Jest is a JavaScript testing framework developed by Facebook. It’s widely used for testing React applications, but it can be used with any JavaScript project. Jest makes it easy to write unit tests, providing a simple API and powerful features like mocking and snapshot testing.


To get started with Jest, you’ll need to install it as a development dependency:


npm install --save-dev jest

Next, create a test file for your code. For example, if you have a sum.js file, create a corresponding sum.test.js file:


// sum.js
function sum(a, b) {
  return a + b;
}
module.exports = sum;

// sum.test.js
const sum = require('./sum');

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

Run your tests using the jest command:


npx jest

If everything is set up correctly, you should see a success message indicating that your test passed.


Getting Started with Cypress for End-to-End Testing


Cypress is a powerful end-to-end testing framework that makes it easy to write and run tests that simulate user interactions with your web application. It provides a rich API for interacting with your application and offers features like time travel debugging and automatic waiting.


To get started with Cypress, install it as a development dependency:


npm install --save-dev cypress

Open Cypress using the cypress open command:


npx cypress open

This will open the Cypress Test Runner, where you can create and run tests. Create a new test file in the cypress/integration directory:


// cypress/integration/sample_spec.js
describe('My First Test', () => {
  it('Visits the Kitchen Sink', () => {
    cy.visit('https://example.cypress.io')
    cy.contains('type').click()
    cy.url().should('include', '/commands/actions')
    cy.get('.action-email')
      .type('fake@email.com')
      .should('have.value', 'fake@email.com')
  })
})

Run your tests in the Cypress Test Runner, and you’ll see your test actions executed in real-time.


Embracing Best Practices


To make the most out of Jest and Cypress, follow these best practices:


1. Write Clear and Descriptive Tests


Your test cases should be easy to understand and describe the behavior you’re testing. This helps others (and your future self) understand what the test is verifying.


// Bad
test('works', () => {
  expect(sum(1, 2)).toBe(3);
});

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

2. Keep Tests Small and Focused


Each test should verify a single piece of functionality. This makes tests easier to read and maintain, and it helps isolate failures to specific features.


// Bad
test('adds numbers and checks for negative values', () => {
  expect(sum(1, 2)).toBe(3);
  expect(sum(-1, -2)).toBe(-3);
});

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

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

3. Use Mocking and Stubbing Wisely


Mocking and stubbing can help isolate the code under test by replacing dependencies with controlled replacements. Jest provides powerful mocking capabilities to help with this.


const fetchData = require('./fetchData');
jest.mock('./fetchData');

test('fetches data successfully', async () => {
  fetchData.mockResolvedValue({ data: 'mockData' });
  const data = await fetchData();
  expect(data).toEqual({ data: 'mockData' });
});

4. Run Tests in Isolation


Ensure that tests don’t depend on each other. Each test should set up its own environment and data, so it can run independently of other tests.


beforeEach(() => {
  // Set up initial state
});

test('first test', () => {
  // Test logic
});

test('second test', () => {
  // Test logic
});

5. Continuous Integration


Integrate your tests into your continuous integration (CI) pipeline to ensure that tests run automatically on every push or pull request. This helps catch bugs early and ensures that your codebase remains stable.


# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Set up Node.js
        uses: actions/setup-node@v2
        with:
          node-version: '14'
      - run: npm install
      - run: npm test

The Gyld’s Commitment to Quality


At The Gyld, we prioritize code quality and reliability. Automated testing with Jest and Cypress is a key part of our development process. By following best practices and integrating tests into our CI pipeline, we ensure that our applications are robust, maintainable, and free of critical bugs.


We continually review and improve our testing strategies, participate in code reviews, and stay updated with the latest testing tools and techniques. This commitment to quality allows us to deliver exceptional software and maintain the trust of our clients.


Conclusion


Automated testing with Jest and Cypress is essential for maintaining high-quality web applications. By writing clear and focused tests, using mocking and stubbing wisely, and integrating tests into your CI pipeline, you can ensure that your code is reliable and maintainable.


Stay tuned for the next post in our series, where we’ll explore package management with npm and Yarn. Until then, keep learning, stay curious, and embrace change. That’s the Gyld way.