代码之家  ›  专栏  ›  技术社区  ›  Yossi

异步函数的笑话

  •  0
  • Yossi  · 技术社区  · 7 年前

    我正在测试包含异步函数的代码。即使在测试不使用await的流时,测试也会失败。当我删除async/await(这是可能的,因为测试流不需要它),测试通过。

    我已经构建了一个代码和测试的简化示例。

    (1) 使用async/await的代码示例(虽然不需要这样做,就像在我测试的流程中一样):

    import React from 'react'
    
    export class Example extends React.Component {
      state = { first: false }
    
      async func1 () {
        const selection = await this.func2()
        this.setState({ first: selection })
      }
    
      async func2 () {
        return true
      }
    
      render () {
        return null
      }
    }
    

    import React from 'react'
    
    export class Example extends React.Component {
      state = { first: false }
    
      func1 () {
        const selection = this.func2()
        this.setState({ first: selection })
      }
    
      func2 () {
        return true
      }
    
      render () {
        return null
      }
    }
    

    这是失败的测试(第三次 expect

    import React from 'react'
    import { shallow } from 'enzyme'
    import { Example } from '../../src/scenes/Recommendation/Patterns/Example'
    
    let wrapper
    
    describe('Testing Example', () => {
      it('calls func1 properly', async () => {
        wrapper = shallow(
          <Example />
        )
        const instance = wrapper.instance()
    
        const prevState = { first: false }
        const expectedState = { first: true }
    
        expect.assertions(2)
        expect(instance.state).toEqual(prevState)
        await instance.func1()
        expect(instance.state).toEqual(expectedState)
      })
    })
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   pengcheng95    7 年前

    你能解释一下你的测试失败的原因吗?是第一种期待还是第二种期待?

    expect.assertions(2);
    

    在测试函数的开始,它等待异步函数完成运行。

        2
  •  0
  •   Bulkan    7 年前

    this 承诺不兑现的问题。

    尝试将更新测试用例添加到以下内容

    describe('Testing Example', () => {
      function flushPromises() {
        return new Promise(resolve => setImmediate(resolve));
      }
    
      it('calls func1 properly', async () => {
        wrapper = shallow(
          <Example />
        )
        const instance = wrapper.instance()
    
        const prevState = { first: false }
        const expectedState = { first: true }
    
        expect.assertions(2)
        expect(instance.state).toEqual(prevState)
        await instance.func1()
        await flushPromises();
        expect(instance.state).toEqual(expectedState)
      })
    });