azl397985856 / fe-interview

宇宙最强的前端面试指南 (https://lucifer.ren/fe-interview)
Apache License 2.0
2.83k stars 260 forks source link

【每日一题】- 2020-05-13 - 异步测试用例 #126

Closed azl397985856 closed 4 years ago

azl397985856 commented 4 years ago

如果你写过单元测试,可能知道单元测试中既需要对同步结果进行断言,也需要对异步结果进行断言。比如同步的情况:

test('#1', () => {
    expect(name).toBe('lucifer')
})

也可能是异步的情况,这里我们需要显式调用done:


test('#1', done => {
    function cb(name) {
        try {
            expect(name).toBe('lucifer')
            done()
        } catch(error) {
            done(error)
        }

    }  
    fetchData(cb)
    expect(name).toBe('lucifer')
})

或者Promise 的形式:


test('#1', () => {
    expect(name).toBe('lucifer')
    return fetchData().then(name => expect(name).toBe('lucifer'))
})

更复杂一点的话, 如果一个异步函数有两个异步断言,我们可能需要这么做:

expect.assertions(2)

function cb1() {
   expect(name).toBe('lucifer')
}
function cb1() {
   expect(age).toBe(17)
}

fetchData(cb1, cb2)

上面的代码是说,这个异步方法有两个异步断言,不要一个走完你就结束了,等我全部走完再结束。

那么问题来了, 上面异步测试的几种方式实现的原理是什么?如果让你实现,你会怎么做?

扩展:

stale[bot] commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.