When it comes to JavaScript testing, there are various tools and frameworks available depending on what you need to test (e.g., unit tests, integration tests, end-to-end tests). Below is a guide on the different types of testing in JavaScript and how you can approach them:
Unit Testing
// math.jsfunction add(a, b) {
return a + b;
}
module.exports = add;
// math.test.jsconst add = require('./math');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
Integration Testing
const request = require('supertest');const app = require('./app'); // Your Express apptest('GET /api/users returns users', async () => {
const response = await request(app).get('/api/users');
expect(response.statusCode).toBe(200);
expect(response.body).toBeDefined();
});
End-to-End (E2E) Testing
// cypress/integration/example_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');
});
});
Snapshot Testing
import React from 'react';import renderer from 'react-test-renderer';import Button from './Button';
test('Button component matches the snapshot', () => {
const tree = renderer.create(<Button label="Click me" />).toJSON();
expect(tree).toMatchSnapshot();
});
Mocking and Spying
const myFunction = jest.fn();
myFunction('arg1');expect(myFunction).toHaveBeenCalledWith('arg1');
Coverage Reporting
jest --coverage
Continuous Integration (CI)
name: Node.js
CIon: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2-
name: Use Node.js
uses: actions/setup-node@v2
with: node
-version: '14'
- run: npm install
- run: npm test
Best Practices
JavaScript testing can be as simple or as comprehensive as needed, depending on your project. Start with unit testing to cover individual functions, and then expand to integration and end-to-end testing to ensure your entire application works as expected. Use the right tools and practices to make your tests maintainable, reliable, and useful.