gpt4 book ai didi

node.js - 如何使用原型(prototype)在nodejs中对以下方法进行单元测试?

转载 作者:太空宇宙 更新时间:2023-11-04 00:00:36 24 4
gpt4 key购买 nike

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 和 z 调用的。
  2. 结果数组由 result1result2 填充。

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

最佳答案

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

const Client = function() {};

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

然后你可以轻松测试是否使用sinon stubs & spies ,我正在使用 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);
})

关于node.js - 如何使用原型(prototype)在nodejs中对以下方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54878118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com