You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Mocha和Chai测试参数化方法是否正确抛出异常?

没问题,我来给你一步步讲清楚怎么用 Mocha + Chai 测试这个函数的异常抛出逻辑~

第一步:先安装依赖

首先确保你已经在项目里安装了开发依赖:

npm install --save-dev mocha chai

第二步:编写测试文件

假设你的 verifyArg 函数放在 utils.js 里,那我们新建一个测试文件,比如 verifyArg.test.js,内容如下:

方式一:用 Chai 的 expect 风格(最常用)

// 导入依赖和目标函数
const { expect } = require('chai');
const verifyArg = require('./utils'); // 替换成你实际的文件路径

// 定义测试套件
describe('verifyArg function', () => {
  // 测试异常抛出的情况
  it('should throw an Error with message "Bad Parameter!" when x equals 400', () => {
    // 重点:必须把函数调用包裹在匿名函数里,让 Chai 去执行它并捕获异常
    // 直接写 verifyArg(400) 会让函数立即执行,异常会直接中断测试,Chai 捕获不到
    expect(() => verifyArg(400)).to.throw(Error, 'Bad Parameter!');
  });

  // 测试正常情况(不抛出异常)
  it('should NOT throw any error when x is not 400', () => {
    expect(() => verifyArg(200)).not.to.throw();
    expect(() => verifyArg('hello')).not.to.throw();
    expect(() => verifyArg(null)).not.to.throw();
  });
});

方式二:用 Chai 的 should 风格

如果你更喜欢链式的 should 语法,也可以这么写:

const should = require('chai').should();
const verifyArg = require('./utils');

describe('verifyArg function', () => {
  it('should throw an Error with message "Bad Parameter!" when x equals 400', () => {
    // 同样要包裹在匿名函数里
    (() => verifyArg(400)).should.throw(Error, 'Bad Parameter!');
  });
});

第三步:运行测试

在你的 package.json 里添加测试脚本:

{
  "scripts": {
    "test": "mocha"
  }
}

然后在终端执行:

npm test

这样就能看到测试结果啦,Mocha 会告诉你两个测试用例是否通过~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:31:21