使用 googleapi 方法反应测试组件

React test component with googleapi method

我正在尝试测试调用 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。是否可以在测试环境中覆盖该函数以模拟对 google API 的调用?

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

您可以将对 axios.post() 的调用替换为一个存根,该存根可以解决或拒绝您为该测试用例定义的内容。这样您就可以针对失败和成功的请求测试您的实现。看看 sinon that helps with mocking. Especially have a look at stub.resolves() and stub.rejects() in the stubs.