laketuna
laketuna

Reputation: 4080

Mocha unit testing: where to create variables

I'm just getting into unit testing for the first time. Using Mocha in Node as the testing framework. All the examples I've come across create variables inside the it(). Does it matter if they are created inside or outside of it()? For example, if I have multiple it()s inside a describe(), and I need the same mocked data across all of the it()s. I'd rather not re-create the same variable repeatedly, if possible.

describe ('MyClass', function () {
    let myObj = new MyObj // Mock data here
    it ('Should be...', function () {
        ....
    })
    it ('Should be...', function () {
        ....
    })
    ...
})

Upvotes: 0

Views: 130

Answers (1)

Nick Tomlin
Nick Tomlin

Reputation: 29211

It's totally acceptable to have variables live outside of your individual it blocks, but it may not be appropriate depending on your use case.

For objects that you do not expect to change, Object.freeze is an option: const myObj = Object.freeze(new MyObj).

If you expect your tests to change your object, you should use beforeEach to ensure that they are restored to the proper state; this will prevent your it blocks from polluting one another and avoid an unpleasant debugging journey.

For example:

describe('MyClass', function () {
  let myObj

  beforEach(() => {
    myObj = new MyObj()
  })

  it('changes myObj', () => {
    changeProp(myObj.sum)
    expect(myObj.sum).toEqual(4)
  })

  it('depends on myObj being the same', () => {
    expect(myObj.sum).toEqual(2)
  })
})

Alternately, you can eschew the fat arrow syntax and rely on the shared context between blocks in mocha:

beforeEach(function () {
  this.myObj = new MyObj()
})

it('changes myObj', function () {
  addTwo(this.myObj.sum)
  expect(this.myObj.sum).toEqual(4)
})

it('depends on myObj being the same', function () {
  expect(this.myObj.sum).toEqual(2)
})

Upvotes: 4

Related Questions