【问题标题】:Asynchronous tests using jest and only callbacks使用 jest 和仅回调的异步测试
【发布时间】:2021-09-16 07:40:57
【问题描述】:

我正在尝试使用 jest 和仅回调来实现一些异步测试。我设法编写了这段代码,我希望它是正确的(它通过了测试):

test('Test the then() clause', function (done) {
    expect.assertions(1);
    const result = generate();
    new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(result);
        }, 100);
    }).then((data) => {
        expect(data).toBe(result);
        done();
    });
});

但是当我期望捕获错误时,我一直在尝试创建测试,就像这样:

test('Test unhandled promise rejection', function (done) {
    expect.assertions(1);
    try {
        new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject('errorrrrr');
            }, 100);
        });
    } catch (error) {
        console.log(error);
        done();
    }
});

我做错了什么?

【问题讨论】:

    标签: javascript node.js jestjs


    【解决方案1】:

    编辑:如果你想通过回调来做到这一点,那么只需摆脱 try/catch

    test('Test unhandled promise rejection', function (done) {
        new Promise(function (resolve, reject) {
                setTimeout(function () {
                    reject('errorrrrr');
                }, 100);
        }).catch(() => {
          console.log(error);
          done();
        });
    });
    

    你需要等待承诺,否则它不会抛出

    test('Test unhandled promise rejection', async function (done) {
        expect.assertions(1);
        try {
            await new Promise(function (resolve, reject) {
                setTimeout(function () {
                    reject('errorrrrr');
                }, 100);
            });
        } catch (error) {
            console.log(error);
            done();
        }
    });
    

    因此,跳过回调并使用resolves/rejects 会更容易(IMO)

    test('Test unhandled promise rejection', async () => {
        await expect(new Promise(function (resolve, reject) {
                setTimeout(function () {
                    reject('errorrrrr');
                }, 100);
        }).rejects.toMatch('errorrrrr')
    });
    

    【讨论】:

    • 我明白这一点,但我不想使用异步和等待。我真正的问题是在没有承诺的情况下实现的,所以 asyn/await 不起作用。我提供了一个简单的代码来“模拟”我的真正问题。这就是我使用 done() 的原因。
    • @ClecioJung - 已编辑。不要使用 try/catch,但如果你是真正的代码不使用承诺,我看不出你提供的模拟代码是如何相关的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    相关资源
    最近更新 更多