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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With