扔进了摩卡咖啡测试中未被捡起

时间:2019-09-18 19:46:22

标签: typescript chai

尽管所有记录器消息都在打印,但我不理解为什么我的测试失败:

it('should reject subscription to a invalid path', async () => {
    const client = fayeConfig.client;
    let subscription: any;

    expect(() => {
        subscription = client.subscribe('/bad_path', (msg: Object) => {
            // do nothing
        });

        subscription.then(() => {
            // 'This should never happen.
            subscription.cancel();
        }, (error: Object) => {
            subscription.cancel();
            logger.debug(`my error ${error}`);
            throw new Error(error.toString());
        }).catch((err: Error) => {
            subscription.cancel();
            logger.debug('something is fishy '+err);
            throw err;
        });
    }).to.throw();
});

我希望错误会冒出来。任何帮助表示赞赏。干杯!

1 个答案:

答案 0 :(得分:0)

问题是expect正在使用同步功能,而我正在提供Promise。因此,它将调用该函数,然后继续。为了解决这个问题,我不得不将函数调用包装在一个单独的函数中,然后等待它解决。

it('should reject subscription to a invalid path', async () => {
    const client = fayeConfig.client;
    let subscription: any;

    const testPromise = async () => {
        subscription = client.subscribe('/bad_path', (msg: Object) => {
            // do nothing
        });

        return subscription.then(() => {
            subscription.cancel();
        }, (error: any) => {
            subscription.cancel();
            throw new Error(`This is the correct behaviour : ${error}`);
        });
    };

    let test: any = null;

    try {
        await testPromise();
    } catch (error) {
        test = error;
    }

    expect(test).to.be.not.null;
});