You need to enable JavaScript to run this app. 使用mocha/chai测试函数是否被传入2个参数调用
优惠活动
大模型
产品
解决方案
定价
更多

使用mocha/chai测试函数是否被传入2个参数调用

Mocha/Chai 校验函数调用参数数量测试用例编写方案

首先明确测试场景:你需要验证的是调用Encrypt函数时传入的实参数量为2,而非函数定义的形参数量,推荐优先使用Sinon.js做函数监听,也可以选择无依赖的原生实现:


方案1:使用Sinon.js(推荐,适配绝大多数单元测试场景)

前置依赖安装

npm i sinon chai-sinon -D

测试文件引入配置

const sinon = require('sinon');
const chai = require('chai');
const expect = chai.expect;
chai.use(require('chai-sinon'));

测试用例代码

it('EncryptCode function call with 2 arguments', () => {
  // 生成spy监听Encrypt函数的调用行为
  const encryptSpy = sinon.spy(EncryptCode, 'Encrypt');
  // 执行函数调用
  EncryptCode.Encrypt('fArgs', 'sArgs');
  
  // 断言1:直接校验调用时参数数量为2
  expect(encryptSpy.firstCall.args.length).to.equal(2);
  // 断言2:也可同时校验参数值是否符合预期(可选)
  expect(encryptSpy).to.have.been.calledWithExactly('fArgs', 'sArgs');

  // 恢复原函数,避免污染其他测试用例
  encryptSpy.restore();
});

方案2:无第三方依赖的原生实现

如果你不想引入额外工具库,可以手动重写函数做参数统计:

it('EncryptCode function call with 2 arguments', () => {
  let receivedArgCount = 0;
  // 暂存原函数
  const originalEncrypt = EncryptCode.Encrypt;
  // 临时重写函数统计参数
  EncryptCode.Encrypt = function(...args) {
    receivedArgCount = args.length;
    return originalEncrypt.apply(this, args);
  };

  // 执行函数调用
  EncryptCode.Encrypt('fArgs', 'sArgs');
  // 断言参数数量
  expect(receivedArgCount).to.equal(2);

  // 恢复原函数
  EncryptCode.Encrypt = originalEncrypt;
});

额外说明

如果你只需要校验Encrypt函数定义的形参数量为2,不需要校验调用时的实参,直接用下面的单条断言即可:

expect(EncryptCode.Encrypt.length).to.equal(2);

内容的提问来源于stack exchange,提问作者Amit Levi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 13:15:04