Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

278
Vistas
How can I test this function using Jest framework?

I have function below. I can't test this function using Jest framework.

The function:

const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;



exports.xhrExample = function() {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'url' , true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var response = JSON.parse(xhr.responseText);
            console.log('Some text');
            console.log('Some text');
        }
    };

    xhr.send(/*body*/);
}

The test:

/**
 * @jest-environment jsdom
 */
const { xhrExample } = require('../function/exampleXHR');

const open = jest.fn();
const setRequestHeader = jest.fn();
const send = jest.fn();
const status = 200;
const readyState = 4;

const xhrMockClass = function () {
        return {
        open,
        setRequestHeader,
        send,
        status,
        readyState
    };
};

global.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass);

test('Should make a request', () => {
    xhrExample();
})

In particular I can't cover if branch. How can I write the right test? I've seen many solutions but they don't work. I also used the xhr-mock utility but it still not working. Thanks to all.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I will create an HTTP server to test it instead of mocking. Your code doesn't make sense, I did some refactoring and added opts parameters for xhrExample function. It's more generic and easier to test.

E.g.

exampleXHR.js:

const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

exports.xhrExample = function (opts) {
  var xhr = new XMLHttpRequest();
  xhr.open(opts.method, opts.url, true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var response = JSON.parse(xhr.responseText);
      opts.onSuccess(response);
    }
  };
  xhr.send();
};

exampleXHR.test.js:

const http = require('http');
const { xhrExample } = require('./exampleXHR');

describe('71021143', () => {
  let server;
  beforeEach((done) => {
    server = http
      .createServer((req, res) => {
        const body = JSON.stringify({ name: 'amelia' });
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(body),
        });
        res.write(body);
        res.end();
      })
      .listen(8000, done);
  });
  afterEach((done) => {
    server.close(done);
  });
  test('should pass', (done) => {
    expect.assertions(1);
    xhrExample({
      method: 'POST',
      url: 'http://localhost:8000',
      onSuccess: (res) => {
        console.log(res);
        expect(res).toEqual({ name: 'amelia' });
        done();
      },
    });
  });
});

Test result:

 PASS  stackoverflow/71021143/exampleXHR.test.js (7.859 s)
  71021143
    ✓ should pass (37 ms)

  console.log
    { name: 'amelia' }

      at Object.onSuccess (stackoverflow/71021143/exampleXHR.test.js:28:17)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |     100 |      100 |     100 |     100 |                   
 exampleXHR.js |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.41 s
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda