Is there a way to get Chai working with asynchronous Mocha tests?

后端 未结 13 2210
自闭症患者
自闭症患者 2020-11-29 21:06

I\'m running some asynchronous tests in Mocha using the Browser Runner and I\'m trying to use Chai\'s expect style assertions:

window.expect = chai.expect;
d         


        
13条回答
  •  孤街浪徒
    2020-11-29 21:17

    Here are my passing tests for ES6/ES2015 promises and ES7/ES2016 async/await. Hope this provides a nice updated answer for anyone researching this topic:

    import { expect } from 'chai'
    
    describe('Mocha', () => {
      it('works synchronously', () => {
        expect(true).to.equal(true)
      })
    
      it('works ansyncronously', done => {
        setTimeout(() => {
          expect(true).to.equal(true)
          done()
        }, 4)
      })
    
      it('throws errors synchronously', () => {
        return true
        throw new Error('it works')
      })
    
      it('throws errors ansyncronously', done => {
        setTimeout(() => {
          return done()
          done(new Error('it works'))
        }, 4)
      })
    
      it('uses promises', () => {
        var testPromise = new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve('Hello')
          }, 4)
        })
    
        testPromise.then(result => {
          expect(result).to.equal('Hello')
        }, reason => {
          throw new Error(reason)
        })
      })
    
      it('uses es7 async/await', async (done) => {
        const testPromise = new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve('Hello')
          }, 4)
        })
    
        try {
          const result = await testPromise
          expect(result).to.equal('Hello')
          done()
        } catch(err) {
          done(err)
        }
      })
    
      /*
      *  Higher-order function for use with async/await (last test)
      */
      const mochaAsync = fn => {
        return async (done) => {
          try {
            await fn()
            done()
          } catch (err) {
            done(err)
          }
        }
      }
    
      it('uses a higher order function wrap around async', mochaAsync(async () => {
        const testPromise = new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve('Hello')
          }, 4)
        })
    
        expect(await testPromise).to.equal('Hello')
      }))
    })
    

提交回复
热议问题