Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent "polluting" variables in a Jest test?

My test looks like this:

const aframeViewer = new VRMaker.AframeViewer()
let el
let panoramas
let panorama

beforeEach(() => {
  panorama = { objectId: '1' }
  panoramas = [panorama]
  el = 'vrmaker-aframe'
})

describe('commonViewer', () => {

  it('addPanoramas', () => {
    const oldPanoramas = clone(panoramas)
    aframeViewer.addPanoramas([{ objectId: '2' }])
    expect(aframeViewer.getPanoramas()).not.toBe(oldPanoramas)
  })

  it('getPanoramas', () => {
    expect(aframeViewer.getPanoramas()).toBe(panoramas)
  })

  it('getCurrentPanorama', () => {
    expect(aframeViewer.getCurrentPanorama()).toBe(panorama)
  })
}) 

The problem here is that aframeViewer.addPanoramas([{ objectId: '2' }]) turns this:

[{ objectId: 1 }]

Into this

[{ objectId: 1 }, { objectId: '2' }]

Therefore the getPanoramas test has a polluted variable. (getCurrentPanorama suffers from the same problem.)

What's the best way to avoid these kind of situations?

like image 962
alex Avatar asked Jan 31 '26 23:01

alex


1 Answers

  1. Declare let aframeViewer; and in the beforeEach add:

    aframeViewer = new VRMaker.AframeViewer()

  2. Don't count on one test to run before another test, make sure to do whatever you need to do either in beforeEach or at the beginning of the test.

like image 118
Nir Alfasi Avatar answered Feb 03 '26 13:02

Nir Alfasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!