簡體   English   中英

如何使用Chai捕獲事件錯誤

[英]How to catch event errors using chai

我正在寫一個打字稿庫。 它公開了以下功能:

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()。 我傳遞了一個錯誤的輸入並將其拋出(它發出“錯誤”事件以及一個新的Error )。 這是我的代碼:

// 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。 也許可能會有所幫助,但我不知道如何將此示例應用於我的案例。

找到了問題。 基本上,我沒有編譯tsc文件,因此我正在執行的舊版本代碼無法正常工作。 這是工作代碼:

it('should throw when the dictionary is not set', (done) => {

  responseGiver.on('error',function(){
    done();
  });

  responseGiver.getMessage("A");

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM