Is it okay if unit tests depend on each other?

Viewed 1751

What if tests share and mutate some common state, and their logic depends on previous tests? Is it acceptable practice? Simple code for example (js):

describe('Some tests', () => {
  const state = {
    value: 'test'
    addMe() {
      this.value = this.value + ' me'
    }
    addPlease() {
      this.value = this.value + ', please'
    }
  }

  it('Some test', () => {
    state.addMe()
    expect(state.value).toBe('test me')
  })

  it('Another test', () => {
    state.addPlease()
    expect(state.value).toBe('test me, please')
  })
})
1 Answers

Typically, tests should be designed not to depend on each other. This is certainly not a law, but a good practice, because it gives your test suite a number of nice properties:

  1. With independent tests, you can add tests at any place, delete tests, re-order tests without unexpected impacts on other tests.

  2. You can improve tests individually without having to think about impact on other tests, for example simplifying the internal working of a test.

  3. Every test can be understood without looking at other tests, and in case of failing tests the reason for the failure is easier to find.

  4. Independent tests succeed and fail individually. With dependent tests, if one test fails, subsequent tests likely also fail.

  5. You can execute your tests selectively, for example to save time during test case execution.

Related