【问题标题】:sinon - check if returned response object matches desired objectsinon - 检查返回的响应对象是否与所需对象匹配
【发布时间】:2017-05-01 09:34:35
【问题描述】:

我正在使用 sinon spy 来监视 HTTP 响应状态并发送。 我在 json 中的“发送”中返回的对象如下:

{
message: 'bla bla',
fields: { request_id ='000', user_id = '3434324' } 
}

如何检查返回的响应是否包含这样的对象、结构和值。

这是我的代码:

var responseStatusSpy = sandbox.spy(res, 'status');
var responseSendSpy = sandbox.spy(res, 'send');
var response_object = {message: "invalid request - no merchant id", fields: {'request_id':'0000', 'user_id' = '2323223'}};

merchantController.getList(req, res);
responseSendSpy.withArgs ?????

提前致谢。

【问题讨论】:

  • sinon.assert.calledExactlyWith(responseSendSpy, response_object )。检查文档的assert 部分:)
  • @VsevolodGoloviznin,我收到错误“sinon.assert.calledExactlyWith”
  • 检查那些方法的参考,我可能拼错了

标签: node.js sinon chai


【解决方案1】:

我提供了一个使用 Express 控制器的工作示例,因为您的代码在某些部分被破坏了。不用担心依赖关系——无论你使用什么框架,原则都是一样的。

controller.js

var express = require('express');
var router = express.Router();

router.get('/example', function(req, res) {

  res.send({
    message: 'bla bla',
    fields: {
      request_id: '000',
      user_id: '3434324'
    }
  });


});


module.exports = router;

test.js

'use strict';

const chai = require('chai');
const sinon = require('sinon');
const SinonChai = require('sinon-chai');

var sinonStubPromise = require('sinon-stub-promise');
sinonStubPromise(sinon);
require('sinon-mongoose');

chai.use(SinonChai);
chai.should();

const mockHttp = require('node-mocks-http');

const controller = require('./controller');


context('Test', () => {


  beforeEach(() => {
    if (!this.sandbox) {
      this.sandbox = sinon.sandbox.create();
    } else {
      this.sandbox.restore();
    }
  });


  it('should pass the test',
    (done) => {

      // Mocking req and res with node-mocks-http
      let req = mockHttp.createRequest({
        method: 'GET',
        url: '/example'
      });

      let res = mockHttp.createResponse({
        eventEmitter: require('events').EventEmitter
      });

      // spy on the response status
      this.sandbox.spy(res, 'send');

      var response_object = {
        message: 'bla bla',
        fields: {
          request_id: '000',
          user_id: '3434324'
        }
      };

      res.on('end', function() {
        try {
          res.send.should.have.been.calledWith(response_object);
          done();
        } catch (e) {
          done(e);
        }
      });

      controller.handle(req, res);

    });

});

首先使用第 3 方 HTTP req / res 模拟库来创建有效的请求和响应对象。接下来在响应的send() 方法上设置一个间谍,并附加一个事件侦听器,以便在响应发送时调用。

那么我们不显式调用控制器的服务方法,而是通过路由器发送请求,这样就可以自然地处理了。

最后,在事件侦听器中设置断言,并根据预期对象验证响应主体。

使用这个秘籍,您可以在路由和实现级别验证快乐/悲伤路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2017-06-28
    相关资源
    最近更新 更多