I have a variable that is needed by various test suites. Rather than initialising in every suite, I have decided to have one test file with a beforeAll
which initialises the variable and split the tests in suite files, which basically export the tests.
For the sake of simplicity let's assume that my test file (the only one jest
calls) is like this:
import { foobar } from './foobar'
let foo
beforeAll(() => {
foo = 'bar'
})
describe('foo is bar', () => {
foobar(foo)
})
and one of my test suite file is like this:
export const foobar = (foo) => {
it('should be defined', () => expect(foo).toBeDefined())
it('should be bar', () => expect(foo).toMatch('bar'))
}
It does not work. foo
is always undefined
and the tests fail.
foo is bar
✕ should be defined (3 ms)
✕ should be bar
What am I missing? I might be having a brain fart day, so excuse me if I am being silly.
Edit (@Estus Flask)
If I define only the check in the imported foobar
file like so:
export const foobar = (foo) => expect(foo).toBeDefined()
and I modify the test file like so:
import { foobar } from './foobar'
let foo
beforeAll(() => {
foo = 'bar'
})
describe('foo is bar', () => {
it('should be defined', () => foobar(foo))
})
It works:
foo is bar
✓ should be defined (2 ms)
So, how is Jest organising the different processes? And also yes, I could put the parameter in the global namespace, but I would like to avoid doing so.
I have found a solution. Rather than passing foo
to the foobar
function, I am exporting it and then importing it where needed.
So, my test file looks like this (with exported foo
)
import { foobar } from './foobar'
export let foo
beforeAll(() => {
foo = 'bar'
})
describe('foo is bar', () => {
foobar()
})
and my test suite file looks like this:
import { foo } from './foo.test'
export const foobar = () => {
it('should be defined', () => expect(foo).toBeDefined())
it('should be bar', () => expect(foo).toMatch('bar'))
}
Now everything passes:
foo is bar
✓ should be defined (1 ms)
✓ should be bar