How can I reset a variable before each iteration?

Viewed 547

I'd like to setup tests for a helper.

The logic is simple: before each test, I create a new item, and apply my function on it.

here is the very basic function:

const myTest = (item) => {
   return item.valid ? 'ok' : 'ko'
}

const createItem = () => {
  return {
    name: 'myItem',
    valid: true,
  }
}

And here is the test file

describe('products/checkStatus', () => {
  let item
  beforeEach(() => {
    item = createItem()
  })

  test('valid item', () => {
    expect(
      myTest(
        item,
      ),
    ).toBe('ok')
  })

  test('invalid item', () => {
    item.valid = false
    expect(
      myTest(
        item
      ),
    ).toBe('ko')
  })

  test('valid item again', () => {
    expect(
      myTest(
        item
      ),
    ).toBe('ok')
  })
})

So, first and second test will pass successfully, but the third one will fail, because it considers that item.valid is false.

How comes so ? Isn't beforeEach supposed to be executed bedore each test, and therefore get a fresh, valid item ?

0 Answers
Related