如何使用原型对nodejs中的以下方法进行单元测试?

问题描述 投票:1回答:1
Client.prototype.a = function(x, y, z) {
    var results = [];
    var result1 = this.foo(x, y, z) ;
    results.push(result1);
    var result2 = this.bar(x, y, z) ;
    results.push(result2);
    return results;
}

我需要进行单元测试:

  1. foobar被称为x, y and z
  2. 结果数组填充了result1result2

我正在使用sinon,但我是sinon测试框架的新手。

node.js unit-testing sinon
1个回答
1
投票

我怀疑你的Client lib看起来像这样:

const Client = function() {};

Client.prototype.foo = () => {};
Client.prototype.bar = () => {};

然后你可以轻松测试是使用sinon stubsspies,我正在使用chai's expect,因为它可以很好地比较数组/对象:

const sinon = require('sinon');
const {expect} = require('chai');

const client = new Client();

// define simple function that just returns args
const returnArgs = (...args) => args;

// stub foo & bar to return args
sinon.stub(client, 'foo').callsFake(returnArgs);
sinon.stub(client, 'bar').callsFake(returnArgs);

it('should call foo & bar', () => {
  const args = [1,2,3];

  const actual = client.a(...args);

  expect(actual).eqls([args, args]);

  expect(client.foo.calledOnce).to.be.true;
  expect(client.foo.getCall(0).args).eqls(args);

  expect(client.bar.calledOnce).to.be.true;
  expect(client.bar.getCall(0).args).eqls(args);
})
© www.soinside.com 2019 - 2024. All rights reserved.