Unit testing with React Native and Mocha

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

Hello, today we are going to see how we can perform Unit Tests using Mocha in React Native.

The first thing we need to do is install the dependencies for testing:

npm install --save-dev mocha chai sinon nyc istanbul-lib-coverage istanbul-reports
npm install --save-dev mocha-junit-reporter
npm install --save-dev @babel/core @babel/register @babel/preset-env

Create a configuration file for test coverage. Create a .nycrc file in the root of your project and add the following content:

{
  "all": true,
  "reporter": [
    "lcov",
    "text-summary"
  ],
  "report-dir": "coverage"
}

This configures the generation of the coverage report in the coverage directory.

Modify the test command in the package.json file:

"scripts": {
  "test": "nyc mocha --require @babel/register test/*.js --reporter mocha-junit-reporter",
  "test_console": "nyc --reporter=lcov mocha --require @babel/register test/*.js"
}

In this example, it is assumed that your test files are located in the test folder and have the .js extension. You can adjust the path and file pattern as needed.

Create a file named .babelrc

{
    "presets": [
        "@babel/preset-env"
    ]
}

Create the test folder and add a file named login_test.js

const { expect } = require('chai');
const axios = require('axios');
const sinon = require('sinon');

const serviceContext = require('../context/serviceContext');

describe('Login tests', () => {
  before(() => {
    sinon.stub(axios, 'post').resolves({ data: { token: 'example_token' } });
  });

  after(() => {
    axios.post.restore();
  });

  it('should make a successful login call', async () => {
    const email = 'example@example.com';
    const password = 'password123';

    const response = await serviceContext.login(email, password);

    expect(response).to.have.property('token').to.equal('example_token');
  });

  it('should handle an error in the login call', async () => {
    axios.post.rejects(new Error('Error in login call'));

    const email = 'example@example.com';
    const password = 'password123';

    try {
      await serviceContext.login(email, password);
    } catch (error) {
      expect(error.message).to.equal('Error in login call');
    }
  });
});

Make sure to adjust the path and file names according to your project’s structure.

To run the tests, invoke:

npm test

(do not include the Reading time). Return it directly in HTML format. Do not add any additional sentences. Add a PIPE at the end when you’re done.

Leave a Comment