javascript - 使用 Sinon 模拟 require() 函数

标签 javascript node.js unit-testing testing mocking

我正在尝试模拟 request-promise在使用 Sinon 的测试中.据我所知,Sinon 模拟对象的方法,而请求 promise 只是返回一个函数。有什么方法可以模拟单个必需的函数吗?

var rp = require('request-promise');
var User = require('../../models/user');

// this works
sinon.stub(User, 'message', function() {});

// This is what I'd like to do to request-promise
sinon.stub(rp, function() {});

我也研究了 mockrequire 和 proxyquire,但我认为它们都遇到了类似的问题。

最佳答案

下面的示例应该可以为您解决问题。通过使用 proxyquire,您可以包装 request-promise 并避免 stub .post.get.call、等。在我看来更干净。

myModule.js:

'use strict';

const rp = require('request-promise');

class MyModule {
  /**
   * Sends a post request to localhost:8080 to create a character.
   */
  static createCharacter(data = {}) {
    const options = {
      method: 'POST',
      uri: 'http://localhost:8080/create-character',
      headers: {'content-type': 'application/json'},
      body: data,
    };
    return rp(options);
  }
}

module.exports = MyModule;

myModule.spec.js:

'use strict';

const proxyquire = require('proxyquire');
const sinon = require('sinon');
const requestPromiseStub = sinon.stub();
const MyModule = proxyquire('./myModule', {'request-promise': requestPromiseStub});

describe('MyModule', () => {
  it('#createCharacter', (done) => {
    // Set the mocked response we want request-promise to respond with
    const responseMock = {id: 2000, firstName: 'Mickey', lastName: 'Mouse'};
    requestPromiseStub.resolves(responseMock);
    MyModule.createCharacter({firstName: 'Mickey', lastName: 'Mouse'})
      .then((response) => {
        // add your expects / asserts here. obviously this doesn't really
        // prove anything since this is the mocked response.
        expect(response).to.have.property('firstName', 'Mickey');
        expect(response).to.have.property('lastName', 'Mouse');
        expect(response).to.have.property('id').and.is.a('number');
        done();
      })
      .catch(done);
  });
});

关于javascript - 使用 Sinon 模拟 require() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32063933/

相关文章:

javascript - Ember.js:如何在组件测试中断言事件未绑定(bind)?

javascript - 如何创建嵌套在 html 内容中的基础弹出窗口(模板)

java - 使用任何传递的参数模拟返回

javascript - 从 Shadow DOM 中获取 ElementById

javascript - 如何在 JavaScript 中访问 anchor 标记?

node.js - 使用 Mongo 和 Node 构建简单的 RESTful API

javascript - Node 脚本中的可用模块

javascript - promise 返回未定义的 Node js

c++ - 使用 cxxtest 框架和 valgrind 测试 qt 对象

javascript - Electron 的单元测试