学习 Jest - 异步测试

测试异步

Promise

可从测试中返回一个 Promise

test('Async Get Data', () => {
    return AsyncGetData().then(data => {
        expect(data).toBe('Data')
    })
})

async / await

test('Await Get Data', () => {
    const data = await AsyncGetData()
    expect(data).toBe('Data')
})

test('Async Get Data', async () => {
    // 断言只有一个 expect 被调用
    // 通常用于 异步测试
    expect.assertions(1)
    try {
        await AsyncGetData()
    }
    catch (e) {
        expect(e).toMatch('error')
    }
})

test('Async Get Data', async () => {
    await expect(AsyncGetData()).resolve.toBe('Data')
    await expect(AsyncGetData()).reject.toMatch('Data')
})

// 如果希望 Promise 被拒绝
// 确保添加了断言
test('Async Get Data Error', () => {
    expect.assertions(1)
    return AsyncGetData().catch(e => expect(e).toMatch('error'))
})

回调

不使用 Promise ,则可以使用回调

// 无法按预期工作
test('Not Useing Promise Useing Callback', () => {
    function cb (err, data) {
        if (err) throw err
        expect(data).toBe('Useing Callback')
    }
    AsyncGetData(cb)
})

// 不要将测试放在 无参函数 中
// 使用接受 done 作为参数的单参数函数
// 将等待回调完成后调用 done 完成测试
// 如果不调用 done,则会发生超时错误
// 语句失败将不会调用 done
// 因此必须使用 try catch 
// 并将错误传递给 catch
// 否则将不会得到错误消息
// 如果想同一测试函数传递 done 并返回 Promise
// 为了避免内存泄漏将会抛出错误
test('Not Useing Promise Useing Callback', done => {
    function cb (err, data) {
        if (err) {
            done(err)
            return
        }
        try {
            expect(data).toBe('Data')
            done()
        } 
        catch (e) {
            done(e)
        }
    }
    AsyncGetData(cb)
})

.resolves / .rejects

// 可以使用 resolves 和 rejects 匹配器
// 必须返回 断言
// 不然会在解析返回的 Promise 之前完成测试
// 然后 AsyncGetData 将有机会执行回调
test('testing resolve and testing reject', () => {
    return expect(AsyncGetData()).resolves.toBe('data')
})

学习 Jest - 异步测试
http://localhost:8080/archives/d2ae0d84-8e27-4dbd-8d87-f1db33def854
作者
inksha
发布于
2024年09月14日
许可协议