node.js - 问题模拟 Node 模块

标签 node.js jestjs

我正在使用 superagent在 React 应用程序中支持一些 XHR 服务。我已经围绕 superagent 编写了一个非常薄的包装器以使配置更容易。事实证明,尝试测试这一薄层非常令人头疼。

我知道有 issues使用 jest 和 node 核心依赖项,我可以通过 dontMocking superagent 的依赖项让事情正常进行。但我更愿意开个 Jest ,只是模拟 superagent 而不会默认爆炸。

结果是我的 package.json 中出现极其冗长的测试介绍或 unMockedModulePatterns 条目,是否有更好的方法?

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

var request = require('superagent');

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

示例测试:

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

最佳答案

我相信更好的方法是写manual mocks ,像这样:

__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');
  });
});

__mocks__/superagent.js:

module.exports = {
  get: jest.genMockFunction()
};

codeundertest.js:

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

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

关于node.js - 问题模拟 Node 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28257722/

相关文章:

node.js - 我怎样才能 Jest 用 es6(没有 typescript )模拟 Prisma 客户端?

node.js - Nodejs - Mongoose 连接到定义的 MongoDB

android - App Engine 中运行的是哪种类型的服务器?

javascript - npm 读取 package.json 后,运行 Electron 的是什么?

javascript - 时间戳在本地机器和 gitlab 管道上的解释不同

javascript - npm 测试没问题,但它也会引发 Uncaught Error AskBackend ReferenceError : localStorage is not defined

javascript - 用 Jest stub 一个函数的函数

node.js - 如何检测socket.io服务器是否已连接?

javascript - 如何使 '@' 符号解析为 src

node.js - MongoDB 连接在测试场景中不会关闭