AssertionError:期望{}是一个函数

时间:2016-02-13 15:40:38

标签: javascript unit-testing mocha chai

我第一次使用Mocha和Chai时遇到了一个奇怪的错误。我之前使用的唯一框架是Jasmine,如果这可以帮助你弄清楚我做错了什么。

我只是想确保我的构造函数不会抛出错误。我已经能够将代码减少到这个,仍然得到错误:

class MyLib {
  constructor() {}
}

export default MyLib;

这是测试文件:

import chai from 'chai';
let { expect } = chai;

import MyLib from '../index';

describe('mylib-js', () => {
  describe('constructor', () => {
    it('should work', () => {
      expect(new MyLib()).to.not.throw();
    })
  });
});

这是Mocha的输出:

d:\path\to\mylib-js>mocha --require babel-core/register


  mylib-js
    constructor
      1) should work


  0 passing (23ms)
  1 failing

  1) mylib-js constructor should work:
     AssertionError: expected {} to be a function
      at Assertion.an (d:\path\to\mylib-js\node_modules\chai\lib\chai\core\assertions.js:169:10)

      at Assertion.assert (d:\path\to\mylib-js\node_modules\chai\lib\chai\utils\addChainableMethod.js:84:49)
      at Assertion.assertThrows (d:\path\to\mylib-js\node_modules\chai\lib\chai\core\assertions.js:1273:32)
      at Assertion.ctx.(anonymous function) [as throw] (d:\path\to\mylib-js\node_modules\chai\lib\chai\utils\addMethod.js:41:25)
      at Context.<anonymous> (test.js:10:4)
      at callFn (C:\Users\Myuser\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:315:21)
      at Test.Runnable.run (C:\Users\Myuser\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:308:7)
      at Runner.runTest (C:\Users\Myuser\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:422:10)
      at C:\Users\Myuser\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:533:12
      at next (C:\Users\Myuser\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:342:14)
      at C:\Users\Myuser\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:352:7
      at next (C:\Users\Myuser\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:284:14)
      at Immediate._onImmediate (C:\Users\Myuser\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:320:5)

我不知道从错误输出中获取{}的位置。它试图告诉我什么?

1 个答案:

答案 0 :(得分:2)

作为异常消息,new MyLib表示对象不是函数。

应该像这样使用throw断言。

expect( () => new MyLib).not.to.throw()