模拟节点模块的问题

Nic*_*lin 4 node.js jestjs

我正在使用superagent来支持反应应用程序中的一些XHR服务.我在superagent上写了一个非常薄的包装器,使配置更容易.试图测试这个薄层已经证明是非常令人头痛的问题.

我知道jest和节点核心依赖性存在问题,我可以dontMock通过superagent的依赖关系来完成工作.但我更喜欢让jest只是模拟superagent而不会在默认情况下爆炸.

结果是unMockedModulePatterns我的package.json中有一个非常详细的测试介绍或输入,有更好的方法吗?

// my-module.js
'use strict';

var request = require('superagent');

module.exports = function () {
  return request.get('http://stackoverflow.com/questions/tagged/jestjs');
};
Run Code Online (Sandbox Code Playgroud)

一个示例测试:

// __tests__/my-module-test.js
'use strict';

jest.dontMock('../');
// T_T
jest.dontMock('superagent');
jest.dontMock('debug');
jest.dontMock('tty');
jest.dontMock('util');
jest.dontMock('stream');
jest.dontMock('fs');
jest.dontMock('delayed-stream');
jest.dontMock('mime');
jest.dontMock('path');

describe('mymodule', function () {
  var myModule, request;

  beforeEach(function () {
    myModule = require('../');
    request = require('superagent');

    request.get = jest.genMockFunction(function () {
      return {
        get: jest.genMockFunction()
      }
    })
  });

  it('makes an xhr request using superagent', function() {
    var req = myModule();
    expect(request.get).toBeCalledWith('http://stackoverflow.com/questions/tagged/jestjs');
  });
});
Run Code Online (Sandbox Code Playgroud)

小智 6

我相信更好的方法是编写手动模拟,如下所示:

__tests __/codeundertest.js:

jest.dontMock('../codeundertest');
describe('whatever', function() {
  it('should do the do', function() {
    var request = require('superagent');

    require('../codeundertest')();
    expect(request.get.mock.calls[0][0]).toBe('http://stackoverflow.com/questions/tagged/jestjs');
  });
});
Run Code Online (Sandbox Code Playgroud)

__mocks __/superagent.js:

module.exports = {
  get: jest.genMockFunction()
};
Run Code Online (Sandbox Code Playgroud)

codeundertest.js:

var request = require('superagent');
module.exports = function () {
  return request.get('http://stackoverflow.com/questions/tagged/jestjs');
};
Run Code Online (Sandbox Code Playgroud)

jest的自动模拟在它工作时非常好但是在很多情况下,编写自己的模拟比尝试支持自动模拟更容易.