【问题标题】:How can I test this function using Jest framework?如何使用 Jest 框架测试此功能?
【发布时间】:2022-02-08 11:19:20
【问题描述】:

我有下面的功能。我无法使用 Jest 框架测试此功能。

功能:

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*/);
}

测试:

/**
 * @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();
})

特别是我无法覆盖 if 分支。如何编写正确的测试?我见过很多解决方案,但它们不起作用。我也使用了 xhr-mock 实用程序,但它仍然无法正常工作。谢谢大家。

【问题讨论】:

标签: javascript unit-testing jestjs mocking xmlhttprequest


【解决方案1】:

我将创建一个 HTTP 服务器来测试它而不是模拟。您的代码没有意义,我做了一些重构并为xhrExample 函数添加了opts 参数。它更通用,更容易测试。

例如

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();
      },
    });
  });
});

测试结果:

 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多