我正在尝试对API调用进行单元测试,以确保已使用正确的属性对其进行了调用。此API调用取决于通过index.html
src="http://stripe[...]"
连接到窗口的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。
答案 0 :(得分:2)
为进行正确的隔离单元测试,应模拟所有不属于被测试单元的单元。如果某个单元属于外部库,则应在window
上对其进行模拟:
const stripeMock = sinon.stub(window, 'stripe');
const redirectToCheckoutMock = sinon.stub();
stripeMock.returns({ redirectToCheckout: redirectToCheckoutMock });