2016-10-31 97 views
0

我有类的持有的属性数组和其中的一些功能。这个类有去除方法去除特定索引的数量:摩卡不抛出错误

class SortedList { 
 
    constructor() { 
 
     this.list = []; 
 
    } 
 

 
    add(element) { 
 
     this.list.push(element); 
 
     this.sort(); 
 
    } 
 

 
    remove(index) { 
 
     this.vrfyRange(index); 
 
     this.list.splice(index, 1); 
 
    }

我为这个类摩卡测试,我想抛出错误时的删除功能参数是负数或大于数组大小。 问题是我无法收到错误消息。我尝试以下方法:

it('check for incorrect input', function() { 
 
      sorted.add(2); 
 
      sorted.add(3); 
 

 
      expect(sorted.remove(-1)).to.throw(Error('Index was outside the bounds of the collection.')) 
 
     });
有人可以帮助我?

+0

您的代码不显式地抛出异常,所以我不希望你的断言通过。如果你想要它,而不是运行时抛出错误,将代码放在remove()中的try块中。 – kinakuta

+0

尝试抓住工作对我来说很好,谢谢。 –

回答

0

将期望抛出Error的函数传递给lambda,并将错误消息作为抛出函数的第二个参数。

it('check for incorrect input', function() { 
 
    list.add(2); 
 
    list.add(3); 
 

 
    expect(() => list.remove(-1)).to.throw(Error, 'Index was outside the bounds of the collection.') 
 
});