3

If I have a spec file like this:

let a;
beforeEach(() => {
   a = 'hello';
})

describe('my test suite', () => {
    test.each([
        [a, 'hello']
    ])(
    'testing %s with expected result %s',
    (myVariable, expectedResult) => {
        expect(myVariable).toBe(expectedResult);
    })
});

I get an error that a is undefined in the parameterized table. If I use a regular test method I have access to a.

1

1 Answer 1

2

You did forget the closing bracket on the beforeEach() line.

let a;
beforeEach(() => {
   a = 'hello';
} );

You also have i% and %1 which is for integers, and you want strings (%s).

With only one test, you do not need the beforeEach() and can simply do:

const a:string = 'hello';
test.each([[a, 'hello']])(
    '.compare(%s, %s)',
    (myVariable, expected) => {
        expect(myVariable).toBe(expected);
    },
);

However, I cannot get this to work either. I can reference the variable directly in the test, such as:

const a:string = 'hello';
test.each([[a, 'hello']])(
    '.compare(%s, %s)',
    (myVariable, expected) => {
        expect(a).toBe(expected);
    },
);

Using your myVariable will not get the value from a inside the closed loop of the test. Literals do work though. The beforeEach would defeat the purpose of setting a value there, as it would not need to be changed in the middle of the test.each() since this is meant to run the same test with different data. You can still create objects and other required things in your beforeEach, and reference them directly (my a variable), but the test data that changes for each run does not seem to get the value from the outside loop.

3
  • sorry I do have more than one test case, just simplified this example to keep the problem at hand concise. I was hoping to reference the variable inside my test cases but doesn't seem to be possible
    – Will Huang
    Commented Oct 25, 2018 at 21:11
  • @WillHuang I could not get it to work. If you are using variables though, you could move the tests into a function and call that. Potentially if your variables are arrays, you can foreach those and do what you are attempting as well. Commented Oct 27, 2018 at 17:21
  • 1
    Yea I got an answer from the Jest team, basically it can't be done. jestjs.io/docs/en/troubleshooting#defining-tests
    – Will Huang
    Commented Oct 29, 2018 at 5:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.