3

我正在编写一个单元测试,我正在模拟一个对象(客户端),它有一个 _request 方法,它需要一个对象和一个回调函数。对象参数有几个具有随机值的属性:

var clientMock = sandbox.mock(client);   // client is defined up somewhere
clientMock
  .expects('_request')
  .withArgs({
    method: 'POST',
    form: {
      commands: [{
        type: "item_add",
        temp_id: '???',       // <== This is random value
        uuid: '???',          // <== Another random value
        args: { ... }
      }]
    }
  }, sinon.match.func);

我该如何为此设置测试?

或者我怎样才能忽略这些特定属性并测试其他属性?

谢谢。

4

1 回答 1

2

sinon.match会帮助你

sandbox.mock(client)
  .expects('_request')
  .withArgs({
    method: 'POST',
    form: {
      commands: [{
        type: "item_add",
        temp_id: sinon.match.string, // As you probably passing String
        uuid: sinon.match.string,    // As you probably passing String
        args: { ... }
      }]
    }
  }, sinon.match.func);

=================

  sandbox.mock(client)
    .expects('_request')
    .withArgs(sinon.match(function(obj) {
      var command = obj.form.commands[0];
      return obj.method === 'POST'
        && command.type === 'item_add'
        && _.isString(command.temp_id)
        && _.isString(command.uuid);
      }, "Not the same!"), sinon.match.func);
于 2015-07-09T14:19:53.500 回答