【问题标题】:React test component with googleapi method使用 googleapi 方法反应测试组件
【发布时间】:2018-08-20 22:15:36
【问题描述】:

我正在尝试测试调用 google API 的组件的方法。 我的代码是下一个:

export default class SubscribeYoutube extends Component {
state = {
    gToken: null
    /*Token obtained after login*/
}
onSubscribe() {
    axios.post('https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&alt=json', {
        "snippet": {
            "resourceId":
                {
                    "channelId": "QuanticoTrends",
                    "kind": "youtube#channel"
                }
        }
    }, {
            headers: {
                "Authorization": this.state.gToken
            }
        })
        .then((response) => {
            this.props.setComplete()
        })
        .catch(error => { })
}
render() {
    return <div>
        {this.state.gToken ?
           <button onClick={this.onSubscribe.bind(this)}>Subscribe</button> 
           :
           <GoogleLogin
                clientId="***clientId***"
                onSuccess={saveTokenInState}
                onFailure={handleError}
                isSignedIn
                tag="span"
                type=""
                scope="profile email https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.force-ssl"/>}
    </div>
}

我的问题是我无法弄清楚如何测试 onSubscribe 方法,因为它会调用 google api。是否可以在测试环境中覆盖该函数以模拟对谷歌 API 的调用?

如果没有令牌,该组件只会呈现一个登录按钮,如果有,则呈现一个订阅按钮。

【问题讨论】:

    标签: reactjs unit-testing tdd jestjs enzyme


    【解决方案1】:

    您可以用一个存根替换对axios.post() 的调用,该存根可以用您自己为该测试用例定义的东西来解决或拒绝。通过这种方式,您可以测试您的实现是否有失败和成功的请求。查看有助于模拟的sinon。尤其是看看stub.resolves()stub.rejects()in the stubs

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2017-05-28
      • 2017-12-06
      • 2019-06-13
      • 2023-03-12
      • 2021-11-03
      相关资源
      最近更新 更多