【问题标题】:How do I test this async method call in reactjs using mocha如何使用 mocha 在 reactjs 中测试此异步方法调用
【发布时间】:2017-11-18 23:34:36
【问题描述】:
// Balance.jsx
...

updateToken () {
  const parseResponse = (response) => {
    if (response.ok) {
      return response.json()
    } else {
      throw new Error('Could not retrieve access token.')
    }
  }

  const update = (data) => {
    if (data.token) {
      this.data.accessTokenData = data
    } else {
      throw new Error('Invalid response from token api')
    }
  }

  if (this.props.balanceEndpoint !== null) {
    return fetch(this.props.accessTokenEndpoint, {
      method: 'get',
      credentials: 'include'
    })
    .then(parseResponse)
    .then(update)
    .catch((err) => Promise.reject(err))
  }
}

componentDidMount () {
    this.updateToken()
    .then(() => this.updateBalance())
  }
}

// Test

it('updates the balance', () => {
  subject = mount(<Balance {...props} />)
  expect(fetchMock.called('balance.json')).to.be.true
})

我不知道如何使用 Mocha 测试上述内容。代码确实有效,方法 updateBalance 被调用并且 fetch api 调用确实发生了,但测试仍然失败。如果我同步调用 updateBalance() 它会通过......我如何告诉测试等待承诺解决?

【问题讨论】:

  • 你能提供updateToken代码吗?
  • 总是return 来自每个函数的承诺。这样你就可以轻松地等待它了。
  • 我已经添加了 updateToken 代码。我确实相信我正在从 updateToken 方法返回一个承诺,因为 fetch api 返回一个承诺,我直接返回它。我想我已经设置好了一切正常工作,我只是不知道如何让摩卡咖啡等待它......
  • @Riina 我认为 Bergi 的意思是您需要将来自updateToken 的承诺返回给调用它的测试函数。看我下面的答案。

标签: node.js reactjs promise mocha.js sinon


【解决方案1】:

你并没有真正说什么你想测试 方法可以,但是如果您只想测试该方法是否在网络调用上解析,则不需要 Sinon 或任何其他,因为这就是您所需要的:

describe("BalanceComponent", () => {
    it("should resolve the promise on a successful network call", () => {
        const component = new BalanceComponent({any: 'props', foo: 'bar'});

        // assumes you call a network service that returns a 
        // successful response of course ...
        return component.updateToken();    
    });
});

这将测试该方法是否确实有效,但它很慢并且不是真正的单元测试,因为它依赖于那里的网络,并且您在可以为您提供工作实现的浏览器中运行测试fetch。一旦您在 Node 中运行它或服务关闭,它就会失败。

如果您想测试该方法是否确实做了特定的事情,那么您需要在测试中传递给then 的函数中进行测试:

    it("should change the token on a successful network call", () => {
        const component = new BalanceComponent({any: 'props', foo: 'bar'});
        const oldToken = component.data.accessTokenData;

        return component.updateToken().then( ()=> {
            assert(oldToken !== component.data.accessTokenData);
        });
    });

如果您想学习如何测试这样的代码而不依赖于您正在调用的网络服务的有效链接,您可以查看three different techniques described in this answer

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    相关资源
    最近更新 更多