我正在写一个打字稿库。它公开了以下功能:
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可能会有所帮助,但我不知道如何将此示例应用于我的案例。
答案 0 :(得分:0)
发现问题。基本上我没有编译tsc文件,所以我执行的代码的旧版本没有工作。这是工作代码:
it('should throw when the dictionary is not set', (done) => {
responseGiver.on('error',function(){
done();
});
responseGiver.getMessage("A");
});