如何对依赖于外部库的 API 进行单元测试 "<script src="http://stripe[...]"

How to unit test an API that depends on an external library "<script src="http://stripe[...]"

我正在尝试对 API 调用进行单元测试,以确保已使用正确的属性调用它。此 API 调用取决于通过 index.html src="http://stripe[...]" 附加到 window 的 Stripe 外部库。我得到 window。[...] 不是函数。

我成功地模拟了 $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 is not a function"。如果我存根 window。 Stripe,然后我在 .redirectToCheckout() 中遇到了类似的错误,正是在这一点上我努力存根。

已经发布了一些与我的代码类似的代码,可以在此处找到 - https://repl.it/@AndrewReinlieb/Checkout-Test

为了进行适当的独立单元测试,所有不属于测试单元的单元都应该被模拟。如果一个单元属于外部库,它应该在 window:

上被模拟
const stripeMock = sinon.stub(window, 'stripe');
const redirectToCheckoutMock = sinon.stub();
stripeMock.returns({ redirectToCheckout: redirectToCheckoutMock });