【问题标题】:Testing async method with mocha and chai使用 mocha 和 chai 测试异步方法
【发布时间】:2017-06-20 03:39:28
【问题描述】:

大家好,我在测试异步函数时遇到了麻烦,其中包含对内部服务器的获取。我正在使用 mocha 和 chai-as-promised。失败的测试是:'返回正确的标题'我想我将不得不模拟 fetch 调用或其他东西,或者问题是我正在调用异步函数,并且当我正在执行单元测试时,我不要解决承诺。我不太确定如何实现这一目标。你能帮帮我吗?

要测试的函数是:

    import React from 'react'
import Technologies from './Technologies'
import fetch from '../../core/fetch'
let title= 'Technologies'
export default {

  path: '/technologies',

  async action () {
    const resp = await fetch('/graphql', {
      method: 'post',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        query: '{technologies{name,icon,url}}',
      }),
      credentials: 'include',
    })
    let { data, } = await resp.json()
    if (!data || !data.technologies) throw new Error('Failed to load technologies.')
    return {
      title:title,
      component: <Technologies title={title} technologies={data.technologies} />,
    }
  },

}

还有我的测试:

describe('Route', () => {

  it('has right path', () => {
    expect(Route.path === '/technologies').to.be.true
  })


  it('return proper title', () => {
    const title = 'Technologies'
    expect(Route.action().title === title).to.be.true
  })
})

【问题讨论】:

    标签: javascript promise mocha.js chai


    【解决方案1】:

    mocha 文档中建议的第一个策略是使用“完成”回调。这是 it 中回调的一个额外参数。您在测试中的最后一个断言之后调用它。

    例如,对于您的测试,您忘记在 expect 中返回函数:

    describe('Route', () => {
    
          it('has right path', (done) => {
            return expect(Route.path === '/technologies').to.be.true
            done();
          })
    
    
          it('return proper title', (done) => {
            const title = 'Technologies'
            return expect(Route.action().title === title).to.be.true
            done();
          })
        })
    

    【讨论】:

      【解决方案2】:

      尝试:

      describe('Route', () => {
      
        it('has right path', () => {
          return expect(Route.path === '/technologies').to.be.true
        })
      
      
        it('return proper title', () => {
          const title = 'Technologies'
          return  expect(Route.action().title === title).to.be.true
        })
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-06
        • 2012-06-29
        • 1970-01-01
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        • 2020-02-28
        • 2013-11-23
        相关资源
        最近更新 更多