我正在尝试对API调用进行单元测试,以确保已使用正确的属性对其进行了调用。此API调用取决于Stripe的外部库,该库通过附加到窗口index.html
src="http://stripe[...]"
。我得到窗口。[...]不是函数。
我成功模拟了该$http.post
请求,但是在从Stripes付款成功进行的回调中,它通过调用window.Stripe()
.redirectToCheckout()将用户重定向回。我设法嘲笑,window.Stripe
但遇到困难,.redirectToCheckout()
不确定如何做到这一点。
index.html:
<script src="https://js.stripe.com/v3/"></script>
<link rel="preconnect" href="https://q.stripe.com">
<link rel="preconnect" href="https://checkout.stripe.com">
StripePayment.vue
async stripe () {
await this.$http.post(process.env.VUE_APP_PAYMENTAPI + 'api/session/', {
amount: this.cost,
}).then(response => {
// Redirect to the main page by using the sessionId provided by stripes response.
window.Stripe(process.env.VUE_APP_STRIPE_KEY).redirectToCheckout({
sessionId: response.body
})
}, response => {
this.paymentFailed(response)
})
}
StripePayment.spec.js
let stripeSpy = sinon.spy(StripePayment.methods, 'stripe')
sinon.assert.calledOnce(stripeSpy)
我希望能够检查API调用是否已成功调用。不幸的是,我收到以下错误消息-“ UnhandledPromiseRejectionWarning:TypeError:window。Stripe不是函数”。如果我存根窗口。Stripe,然后我用.redirectToCheckout()遇到了类似的错误,而这正是我难以进行存根的地方。
有一些类似于我的代码已发布,可以位于此处-https://repl.it/@AndrewReinlieb/Checkout-Test。
为了进行正确的隔离单元测试,应模拟所有不属于被测试单元的单元。如果某个单元属于外部库,则应在以下位置进行模拟window
:
const stripeMock = sinon.stub(window, 'stripe');
const redirectToCheckoutMock = sinon.stub();
stripeMock.returns({ redirectToCheckout: redirectToCheckoutMock });
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句