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

如何修复使用Chai写单元测试时的no-unused-expressions ESLint警告?

触发警告的根本原因

你用到的to.be.true是Chai的getter类型断言属性,没有执行函数调用操作,ESLint的no-unused-expressions规则会误判这行是没有实际作用的表达式,所以触发警告,这也是你把结果存入变量后依然报警告的核心原因。

以下是三种可落地的修复方案:

方案1:替换为带函数调用的断言写法

最简单的无侵入改法,把属性访问形式的断言改成带括号调用的equal方法即可,无需调整ESLint配置:

it('should contain only strings', () => {
  const result = prContributors.every((contributor) => typeof contributor === 'string');
  expect(result).to.equal(true);
});
// 也可以直接简写为:
it('should contain only strings', () => {
  expect(prContributors.every(contributor => typeof contributor === 'string')).to.equal(true);
});

方案2:使用assert接口的方法式断言

如果你用Chai的assert接口,本身都是函数调用形式,天然不会触发该警告:

it('should contain only strings', () => {
  const allIsString = prContributors.every(contributor => typeof contributor === 'string');
  assert.isTrue(allIsString, 'prContributors的所有元素都应为字符串');
});

方案3:配置ESLint适配Chai断言

如果项目里大量用到Chai的属性式断言,可以安装专门的ESLint插件避免全局误判:

  1. 安装依赖:
npm install eslint-plugin-chai-friendly --save-dev
  1. 修改你的ESLint配置文件(.eslintrc.js等):
module.exports = {
  plugins: ['chai-friendly'],
  rules: {
    // 关闭原生的no-unused-expressions规则,换成适配Chai的规则
    'no-unused-expressions': 'off',
    'chai-friendly/no-unused-expressions': 'error'
  }
}

配置后你原来的expect(...).to.be.true写法就不会再触发警告了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:39:01