在CommonJS环境(如Node.js+Mocha/Jest)中,可将断言辅助函数封装于模块中用module.exports导出,通过require引入使用;函数应单一职责、语义清晰、纯函数、兼容Chai或Jest等断言库,并支持TypeScript类型提示。

在 JavaScript 的 CommonJS 环境(如 Node.js + Mocha/Jest 默认 CommonJS 模式)中,你可以把通用的断言辅助函数封装在一个模块里,用 module.exports 导出,然后在测试文件中通过 require() 引入使用。关键是要让这些函数可复用、语义清晰,并与主流断言库(如 Chai、Jest expect、或自定义断言)协同工作。
导出可复用的断言辅助函数
比如你经常需要校验某个异步操作是否抛出特定错误,或检查对象是否包含一组动态键值对,可以写成独立函数并统一导出:
- 新建
test-helpers.js(或assertions.js) - 每个函数只做一件事,接收必要参数,返回布尔值或直接调用断言(推荐后者,便于报错定位)
- 避免副作用,不修改传入对象,保持纯函数特性
示例(基于 Chai):
将一个或多个视频上传至YouTube。当用户想“上传到YouTube”“发YouTube”“批量上传”“upload to YouTube”“post videos to YouTube”或发布到YouTube时使用此技能。
// test-helpers.js
const { expect } = require('chai');
<p>function expectToThrowAsync(fn, expectedErrorType, messageContains) {
return expect(fn()).to.eventually.be.rejected.then(err => {
expect(err).to.be.an.instanceOf(expectedErrorType);
if (messageContains) {
expect(err.message).to.include(messageContains);
}
});
}</p><p>function expectObjectContains(obj, partial) {
Object.keys(partial).forEach(key => {
expect(obj).to.have.property(key);
expect(obj[key]).to.deep.equal(partial[key]);
});
}</p><p>module.exports = {
expectToThrowAsync,
expectObjectContains,
};</p>在测试文件中引入并使用
直接 require 后即可调用,和原生断言一样参与测试流程:
立即学习“Java免费学习笔记(深入)”;
// user.test.js
const { expect } = require('chai');
const { expectToThrowAsync, expectObjectContains } = require('./test-helpers');
<p>describe('User service', () => {
it('should reject with ValidationError when email is invalid', async () => {
await expectToThrowAsync(
() => createUser({ email: 'invalid' }),
Error,
'email'
);
});</p><p>it('should return user with id and name', () => {
const user = { id: 123, name: 'Alice', role: 'user' };
expectObjectContains(user, { id: 123, name: 'Alice' });
});
});</p>适配不同断言库的注意事项
-
Jest 用户:不要在辅助函数里直接调用
expect(...),因为 Jest 的expect是 per-test 绑定的;改用返回布尔值或抛错,再由测试内调用expect(...).toBe(true)或expect(() => ...).toThrow(...) -
Chai 用户:可直接链式调用(如上例),但注意异步函数需配合
.eventually或.and等修饰符 - 若辅助函数内部抛错(如
throw new Error('xxx')),Jest/Chai 都能捕获并显示为测试失败,且保留堆栈信息
进阶:支持 TypeScript 和自动类型提示
即使使用 CommonJS,也可以为 test-helpers.js 添加 .d.ts 声明文件,或在 JS 文件顶部加 JSDoc 注释,让 VS Code 等工具识别参数和返回类型:
/**
* @param {() => Promise<any>} fn
* @param {typeof Error} expectedErrorType
* @param {string} [messageContains]
* @returns {Promise<void>}
*/
function expectToThrowAsync(fn, expectedErrorType, messageContains) {
// ...
}

















