Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
How to mock a 3rd party window object in vue test?

So i have a vue method that i need to test

in CheckoutButton.vue

createMidtransToken () {
  const card = this.$store.state.payment.creditCardPayload
  const options = {
        onSuccess: (response) => {
          // HANDLING SUCCESS
          const payload = {
            ...this.paymentTypeChoosen,
            token: response.token_id
          }
          this.payCheckout(payload)
        },
        onFailure: (response) => {
          // HANDLING ERROR
          const errorMessage = response.status_message
          this.$alertModal.show({
            show: true,
            type: 'error',
            title: 'Transaksi Dibatalkan',
            text: errorMessage,
            showButton: true,
            buttonText: 'Kembali',
            buttonEventExist: true,
            buttonEvent: () => {
              this.handleRouteError()
            }
          })
        }
      }
  window.MidtransNew3ds.getCardToken(card, options)
}

in CheckoutButton.spec.js

it('Should test createMidtransToken', () => {
    Object.defineProperty(window, 'MidtransNew3ds', {
      getCardToken: jest.fn()
    })

    wrapper.vm.createMidtransToken()
    expect(window.MidtransNew3ds.getCardToken).toHaveBeenCalled()
  })
})

and I get an error

● Testing component CheckoutButton with stage summary › Should test createMidtransToken

TypeError: Cannot read property 'getCardToken' of undefined
  362 |         }
  363 |       }
> 364 |       window.MidtransNew3ds.getCardToken(card, options)
      | ^
  365 |     },

How do I test the createMidtransToken method so the file test can run properly?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

defineProperty arguments are incorrect. There should be either get function or value value in config object in order to define a property.

Object.defineProperty(window, 'MidtransNew3ds', {
   value: { getCardToken: jest.fn() }
})

There is no reason to use it here because defineProperty is useful only for specific purposes. It can be defined either per test or in beforeEach for all tests:

window.MidtransNew3ds = { getCardToken: jest.fn() };

And should be always cleaned in afterEach in order to not affect other tests:

delete window.MidtransNew3ds
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!