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.

Realizar pruebas unitarias con React Native y Mocha

Tiempo de lectura: 2 minutos

Hola, hoy vamos a ver cómo podemos realizar pruebas Unitarias usando Mocha en React Native.

Lo primero que tenemos que hacer es instalar las dependencias para las pruebas:

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

Crea un archivo de configuración para la cobertura de pruebas. Crea un archivo .nycrc en la raíz de tu proyecto y agrega el siguiente contenido:

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"
}

Esto configura la generación del informe de cobertura en el directorio coverage.

Modifica la línea de comando de ejecución de tus pruebas en el archivo package.json:

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"
}

En este ejemplo, se asume que tus archivos de prueba se encuentran en la carpeta test y tienen la extensión .js. Puedes ajustar la ruta y el patrón de archivos según sea necesario.

Crea un archivo llamado .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"
    ]
}

Crea la carpeta test y añade un archivo prueba_login.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('Pruebas de login', () => {
before(() => {
sinon.stub(axios, 'post').resolves({ data: { token: 'example_token' } });
});
after(() => {
axios.post.restore();
});
it('debería realizar una llamada de login exitosa', 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('debería manejar un error en la llamada de login', async () => {
axios.post.rejects(new Error('Error en la llamada de login'));
const email = 'example@example.com';
const password = 'password123';
try {
await serviceContext.login(email, password);
} catch (error) {
expect(error.message).to.equal('Error en la llamada de login');
}
});
});
const { expect } = require('chai'); const axios = require('axios'); const sinon = require('sinon'); const serviceContext = require('../context/serviceContext'); describe('Pruebas de login', () => { before(() => { sinon.stub(axios, 'post').resolves({ data: { token: 'example_token' } }); }); after(() => { axios.post.restore(); }); it('debería realizar una llamada de login exitosa', 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('debería manejar un error en la llamada de login', async () => { axios.post.rejects(new Error('Error en la llamada de login')); const email = 'example@example.com'; const password = 'password123'; try { await serviceContext.login(email, password); } catch (error) { expect(error.message).to.equal('Error en la llamada de login'); } }); });
const { expect } = require('chai');
const axios = require('axios');
const sinon = require('sinon');

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

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

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

  it('debería realizar una llamada de login exitosa', 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('debería manejar un error en la llamada de login', async () => {
    axios.post.rejects(new Error('Error en la llamada de login'));

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

    try {
      await serviceContext.login(email, password);
    } catch (error) {
      expect(error.message).to.equal('Error en la llamada de login');
    }
  });
});

Asegúrate de ajustar la ruta y los nombres de archivos según la estructura de tu proyecto.

Para ejecutar las pruebas invoca:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm test
npm test
npm test
0

Deja un comentario