Jasmine测试无法创建类新实例问题排查求助
排查Jasmine测试无法创建Bingo类实例的问题
看起来你在给JS Bingo游戏写Jasmine测试时遇到了实例创建和断言的问题,我帮你梳理下代码里的几个关键问题:
1. 语法错误导致代码解析失败
你代码里的var bin后面漏掉了分号,这会触发语法错误,让Jasmine无法正常执行后续的测试逻辑:
'use strict'; describe('logic(bingo)',function() { var bin // ❌ 这里缺少分号,应该写成 var bin; beforeEach(function() { bin = new Bingo('Alex') }) // ... 其他测试代码 })
2. 第一个测试用例的逻辑错误
你想测试“当name不是字符串时抛出错误”,但当前写法有问题:你先执行了bin=new Bingo()(不传参数),如果Bingo构造函数本身会在参数非法时抛错,这行代码会直接抛出错误,根本到不了后续的expect断言。
正确的做法是把构造函数的调用过程包裹在expect的匿名函数里,这样Jasmine才能捕获到实例化时抛出的错误:
❌ 错误写法:
it('should throw error if name is not a string',function() { bin=new Bingo() // 这里直接抛错,测试提前失败 expect(function() { return bin.name }).toThrowError('Input a string name') })
✅ 修正后写法:
it('should throw error if name is not a string',function() { // 把构造函数调用放在expect的函数内,让Jasmine捕获实例化时的错误 expect(function() { new Bingo(); // 不传参数,触发校验逻辑 }).toThrowError('Input a string name'); })
3. 第二个测试用例的拼写错误
你写的expe...是expect的拼写不全,补全后才能正常执行断言:
it('should board.length===3 and board[0].length===5',function() { expect(bin.board.length).toBe(3); expect(bin.board[0].length).toBe(5); })
完整修正后的测试代码
'use strict'; describe('logic(bingo)', function() { var bin; // 修复语法错误,添加分号 beforeEach(function() { bin = new Bingo('Alex'); }); it('should throw error if name is not a string', function() { expect(function() { new Bingo(); // 将构造函数调用放在expect函数内,捕获实例化错误 }).toThrowError('Input a string name'); }); it('should have a board with 3 rows and 5 columns', function() { expect(bin.board.length).toBe(3); expect(bin.board[0].length).toBe(5); }); });
另外别忘了,你的Bingo类构造函数需要实现对应的参数校验逻辑,否则测试也会失败,比如:
class Bingo { constructor(name) { // 校验name是否为字符串 if (typeof name !== 'string') { throw new Error('Input a string name'); } this.name = name; // 初始化3行5列的棋盘 this.board = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15] ]; } }
内容的提问来源于stack exchange,提问作者Alex G. Borrego
相关产品推荐
相关产品推荐

