【问题标题】:How to catch event errors using chai如何使用 chai 捕获事件错误
【发布时间】:2018-02-11 07:20:15
【问题描述】:

我正在编写一个打字稿库。它公开了以下功能:

export declare function setDictionary(_dictionary: object): void;
export declare function getMessage(error: string): any;
export declare function setLoggerLevel(level: string): void;
export declare function on(event: string, handler: IListener): void;

现在我想用 Mocha 和 Chai 测试函数 getMessage()。我传递了一个错误的输入并让它抛出(它发出一个“错误”事件加上一个新错误)。这是我的代码:

// Imports and Globals
import * as responseGiver from '../index.js';
import { expect } from 'chai';
import 'mocha';

describe('Public functions', () => {
  describe('getMessage(error : string) : any', () => {
    it('should throw when the dictionary is not set', () => {
      expect( function() { responseGiver.getMessage("A") } ).to.throw(new Error("The dictionary is not set"));
    });
  });
});

但是,它不起作用。

  Public functions
    getMessage(error : string) : any
error: The dictionary is not set
      1) should throw when the dictionary is not set


  0 passing (14ms)
  1 failing

  1) Public functions getMessage(error : string) : any should throw when the dictionary is not set:
     AssertionError: expected [Function] to throw 'Error: The dictionary is not set'
      at Context.<anonymous> (js-src/test/test.js:17:83)



npm ERR! Test failed.  See above for more details.

我读过关于堆栈溢出的类似线程,但我仍然不知道如何使它工作以及 chai 在这种情况下如何工作。也许this 可能会有所帮助,但我不知道如何将此示例应用于我的案例。

【问题讨论】:

    标签: javascript unit-testing typescript mocha.js chai


    【解决方案1】:

    发现问题。基本上我没有编译 tsc 文件,所以我执行的是旧版本的代码,它不起作用。这是工作代码:

    it('should throw when the dictionary is not set', (done) => {
    
      responseGiver.on('error',function(){
        done();
      });
    
      responseGiver.getMessage("A");
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-30
      • 2020-10-17
      • 2018-06-04
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多