如何用Jest测试Ship类?测试时出现TypeError错误
解决Ship类测试的模块导入导出问题
先统一模块规范(二选一,别混用)
方案1:用Node.js默认的CommonJS
- ship.js 导出类:
class Ship { constructor(length) { this.length = length; this.hits = 0; } hit() { if (this.hits < this.length) this.hits++; } checkHitsToSink() { return this.hits >= this.length; } } // 导出整个类 module.exports = Ship;
- tests/ship.test.js 导入并测试:
// 注意路径是相对路径,指向你的ship.js文件 const Ship = require('../ship.js'); test('调用hit()会增加命中次数', () => { const testShip = new Ship(3); testShip.hit(); expect(testShip.hits).toBe(1); }); test('命中次数等于长度时船会沉没', () => { const testShip = new Ship(2); testShip.hit(); testShip.hit(); expect(testShip.checkHitsToSink()).toBe(true); });
方案2:用ESM模块(需要改package.json)
- 先在项目根目录的
package.json里添加一行配置,告诉Node.js用ESM:
"type": "module"
- ship.js 导出类(两种导出方式选一种):
- 命名导出:
export class Ship { constructor(length) { this.length = length; this.hits = 0; } hit() { if (this.hits < this.length) this.hits++; } checkHitsToSink() { return this.hits >= this.length; } }
- 默认导出:
class Ship { // 同上构造函数和方法 } export default Ship;
- tests/ship.test.js 导入:
- 对应命名导出:
import { Ship } from '../ship.js';
- 对应默认导出:
import Ship from '../ship.js';
测试逻辑和CommonJS版本完全一致。
踩坑排查要点
- 绝对别对Ship实例用
require():require是用来导入模块文件的,不是实例化对象的,之前的错误就是犯了这个错。 - 导入路径要准确:测试文件在
tests文件夹的话,导入根目录的ship.js必须用../ship.js,路径错了会直接报找不到模块。 - 别混用两种模块规范:CommonJS的
require/module.exports和ESM的import/export不能在同一个项目里混着用(除非用动态import,新手没必要碰)。
最后跑测试
确保你装了测试框架(比如jest),没装的话先跑:
npm install --save-dev jest
然后在package.json的scripts里加:
"test": "jest"
之后直接执行npm test就能正常跑测试了。
内容的提问来源于stack exchange,提问作者Brandyn Coverdill
相关产品推荐
相关产品推荐

