Unit testing Sinon:测试函数返回值

Unit testing Sinon:测试函数返回值,unit-testing,sinon,spy,enzyme,Unit Testing,Sinon,Spy,Enzyme,我正在使用SinonEnzyme进行测试。我有一个函数,它接受一个对象数组并将其转换为一个新的不同数组 getContainersByHostId(data) { return _.chain(data) .groupBy('hostId') .toPairs() .map(currentItem => _.zipObject(['hostId', 'containers'], currentItem)) .value(); }

我正在使用
Sinon
Enzyme
进行测试。我有一个函数,它接受一个对象数组并将其转换为一个新的不同数组

getContainersByHostId(data) {
    return _.chain(data)
      .groupBy('hostId')
      .toPairs()
      .map(currentItem => _.zipObject(['hostId', 'containers'], currentItem))
      .value();
  }
参数:

const containers = [{
          id: 'c_01',
          hostId: 'h_01',
          hostIp: '192.168.1.0',
          name: 'Some Container'
        }];
[{hostId: 'h_01',
containers: [{
hostId: 'h_01',
ip: '192.168.1.0',
id: 'c_01',
name: 'Some Container'
}]}];
结果:

const containers = [{
          id: 'c_01',
          hostId: 'h_01',
          hostIp: '192.168.1.0',
          name: 'Some Container'
        }];
[{hostId: 'h_01',
containers: [{
hostId: 'h_01',
ip: '192.168.1.0',
id: 'c_01',
name: 'Some Container'
}]}];
这个很好用。然而,我面临的问题是单元测试。所以现在我有这个

const containers = [{
          id: 'c_01',
          hostId: 'h_01',
          hostIp: '192.168.1.0',
          name: 'Indigo Container'
        }];

        const wrapper = shallow(<Groups {...props} />);
        const instance = wrapper.instance();
        sandbox.stub(instance, 'getContainersByHostId');
        instance.getContainersByHostId(containers);
        expect(instance.getContainersByHostId.calledWith(containers)).to.equal(true);
      });
const容器=[{
id:'c_01',
hostId:'h_01',
hostIp:'192.168.1.0',
名称:“靛蓝容器”
}];
常量包装器=浅();
const instance=wrapper.instance();
stub(实例'getContainersByHostId');
getContainersByHostId(容器);
expect(instance.getContainersByHostId.calledWith(containers)).to.equal(true);
});
如何测试传递的参数是否等于新数组

更新:

const containers = [{
          id: 'c_01',
          hostId: 'h_01',
          hostIp: '192.168.1.0',
          name: 'Some Container'
        }];
[{hostId: 'h_01',
containers: [{
hostId: 'h_01',
ip: '192.168.1.0',
id: 'c_01',
name: 'Some Container'
}]}];

我已经尝试了
returnValue
,但它给了我false,我找不到任何可能的解决方案来检查它真正返回的内容。

首先,当你存根一个函数时,你会取消它的所有行为,所以如果你没有为这个存根指定要返回的值,那么它将返回
未定义的
。很可能您把它与
sinon.spy()
混淆了

如果我对你的理解正确,你所需要的一切都会更容易实现。根本不需要信农。比如:

const modified = instance.getContainersByHostId(inputArray);    
expect(modified).to.eql(expectedArray);

你到底想断言什么?我想您应该有两个数组,一个用于输入,另一个用于预期输出。因此,您只需断言使用该输入调用
getContainersByHostId
应该返回预期的输出。这就是你想要实现的吗?这正是我想要断言的。但当我针对输出数组断言它时,它给出了未定义的结果。你能给我举个例子说明我是如何做到的吗。也许我做错了什么。我也会修改我的问题好吧,我知道我在做一些非常愚蠢的事情。你是对的。但我不确定我是否明白你的第一点。你说我必须指定返回值的那个点?你能详细说明一下吗?我基本上想理解为什么它首先抛出了
未定义的
,你是说我不必监视或创建类方法的存根?因为,您直接断言了原始函数?我当时的印象是,我们应该用间谍还是存根来做这件事?如果您能详细解释一下,我将非常感激。好的,因为在您的测试用例中有一个手动函数调用:
instance.getContainersByHostId(containers)你不需要监视或存根任何东西。当您不控制函数调用时,将使用存根或监视。在大多数情况下,它们用于调用某个东西时触发spied方法的情况。至于指定返回值,我提到了
stub.returns(obj)
此方法使存根返回提供的值。你可以在这里仔细看看Sinon api:伙计,这真的很有帮助。非常感谢。很高兴能帮助你!:)