使用mocha和chai测试异步方法

时间:2017-02-02 21:45:44

标签: javascript promise mocha chai

大家好我在使用内部服务器获取来测试异步功能时遇到了麻烦。我正在使用mocha和chai-as-promised。失败的测试是:'返回正确的标题'我想我必须嘲笑取消电话或其他东西,或者问题是我正在调用异步功能,而且我正在执行单元测试并且我没有解决这个承诺。我不太确定如何实现这一目标。你能帮帮我吗?

要测试的功能是:

    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
  })
})

2 个答案:

答案 0 :(得分:1)

尝试:

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
  })
})

答案 1 :(得分: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();
      })
    })
相关问题