Reset an object import in a beforeEach

Viewed 29

I want to remember the technical explanation of this behavior and how to do it properly

sample.js (in reality this is a really long mock which is why its in a separate file)

const data = {
  a = 1,
  nested: {
     object: 'old'
  }
}

export default data;

data.spec.js

import sampleData from './sample'

describe('sample', () => {
let data;
 beforeEach(
  data = sampleData
 )
  it('change data', () => {
    data.nested.object = 'new'; // lets say value was old before
    ....
  })
  it('change data', () => {
   console.log(data.nested.object) // i would think it would be 'old' but is still 'new'
    ....
  })

My brain says that its doing so because all i did was add a pointer to the object and i'm still modifying the object so the beforeEach doesn't do anything. I feel like there's a longer explanation that I'm forgetting

But I want to know the proper way to do it. if I turn the sample data file to a function and have it 'return' the object each time That seems right given I use an arrow function. But that feels incorrect. Is there something I'm forgetting?

1 Answers

Your assumption is correct, just don't forget to make a copy of your test data before changing it.

For example:

beforeEach(() => {
  data = structuredClone(sampleData);
});

Or for older ecmascript version:

beforeEach(() => {
  data = { ...sampleData, nested: { ...sampleData.nested } };
});
Related