Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jest testing pass variable to another test

I'm trying to assign a variable from one test to be accessed within another test. For example:

let user;

test('create new user', async () => {
  const response = await createUser()
  user = response
})

test('delete user', async () => {
  const response = await deleteUser(user.id)
})

I understand that jest has a --runInBand option, however this still has user as undefined in "delete user". Any ideas how to accomplish this with jest? Thank you

like image 805
dzm Avatar asked Feb 02 '19 02:02

dzm


1 Answers

Each test runs independently, and for good reason. Tests should be confirming isolated conditions, methods, and logic. All --runInBand does is run the tests in serially, but they still won't necessarily be able to share data objects the way you seem to be expecting.

Also, assuming these methods defer to a backend service of some kind, you're not going to easily be able to fully test the behavior of that system. It sounds like you want an end-to-end or integration testing framework, as opposed to a unit testing framework like Jest.

Keeping with Jest, you're likely going to need to mock whatever backend service is being called in createUser and deleteUser. Jest mocks can help replace external functions with new ones that create the types of conditions you want to test.

Alternatively or in addition, you might be able to stub your user object using beforeAll or beforeEach, creating sample data that allows you to test how deleteUser behaves when it's passed a particular object (likely bypassing whatever backend persistence with an aforementioned mock).

like image 165
benjarwar Avatar answered Oct 30 '22 23:10

benjarwar