如何使用原型对nodejs中的以下方法进行单元测试?
How to unit test following methods in nodejs using prototype?
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;
}
我需要进行单元测试:
foo
和 bar
是用 x, y and z
调用的。
- 结果数组填充了
result1
和 result2
。
我正在使用 sinon,但我是 sinon 测试框架的新手。
我怀疑你的 Client
库看起来像这样:
const Client = function() {};
Client.prototype.foo = () => {};
Client.prototype.bar = () => {};
然后你可以很容易地测试使用 sinon stubs & spies, and I'm using chai's expect,因为它可以很好地比较 arrays/objects:
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);
})
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;
}
我需要进行单元测试:
foo
和bar
是用x, y and z
调用的。- 结果数组填充了
result1
和result2
。
我正在使用 sinon,但我是 sinon 测试框架的新手。
我怀疑你的 Client
库看起来像这样:
const Client = function() {};
Client.prototype.foo = () => {};
Client.prototype.bar = () => {};
然后你可以很容易地测试使用 sinon stubs & spies, and I'm using chai's expect,因为它可以很好地比较 arrays/objects:
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);
})