Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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
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
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"all": true,
"reporter": [
"lcov",
"text-summary"
],
"report-dir": "coverage"
}
{ "all": true, "reporter": [ "lcov", "text-summary" ], "report-dir": "coverage" }
{
  "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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"scripts": {
"test": "nyc mocha --require @babel/register test/*.js --reporter mocha-junit-reporter",
"test_console": "nyc --reporter=lcov mocha --require @babel/register test/*.js"
}
"scripts": { "test": "nyc mocha --require @babel/register test/*.js --reporter mocha-junit-reporter", "test_console": "nyc --reporter=lcov mocha --require @babel/register test/*.js" }
"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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"presets": [
"@babel/preset-env"
]
}
{ "presets": [ "@babel/preset-env" ] }
{
    "presets": [
        "@babel/preset-env"
    ]
}

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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');
}
});
});
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'); } }); });
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm test
npm test
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.

0

Leave a Comment