Reputation: 6943
I am working on a series of jest test scripts, and to make the code a bit tighter, I am putting them in an array:
test('buttonPadding', function () {
const expectedResults = [
{ iconPosition: 'center', small: true, expectedResult: undefined },
{ iconPosition: 'center', small: false, expectedResult: undefined },
{ iconPosition: 'left', small: true, expectedResult: '10px 20px 10px 20px' },
{ iconPosition: 'left', small: false, expectedResult: '17px 42px 18px 42px' },
{ iconPosition: 'right', small: true, expectedResult: '10px 20px 10px 20px' },
{ iconPosition: 'right', small: false, expectedResult: '17px 42px 18px 42px' },
];
expectedResults.forEach(({ iconPosition, small, expectedResult }) => {
expect(buttonPadding({ iconPosition, small })).toEqual(expectedResult);
});
});
The downside is when an error occurs, it shows the expect(buttonPad...
line as where the error occurred, but doesn't show what the parameters were that got passed into the tested function.
Is there something that can be passed to the expect()
function that will allow you to output some type of log when an error occurs so I can see what made the test fail?
What I would like to know is what iconPosition and small were equal to to get the test to fail.
Upvotes: 2
Views: 153
Reputation: 32158
I can also suggest using describe.each or test.each like this:
describe.each(
[
['center', true, undefined],
['center', false, undefined],
['left', true, '10px 20px 10px 20px'],
['left', false, '17px 42px 18px 42px'],
['right', true, '10px 20px 10px 20px'],
['right', false, '17px 42px 18px 42px'],
]
)('with params (%p, %p)', (iconPosition, small, expectedResult) => {
it(`should return: ${expectedResult}`, () => {
expect(buttonPadding({ iconPosition, small })).toEqual(expectedResult);
})
});
Upvotes: 2
Reputation: 6943
Found a better way, and one where tests are more isolated by putting the foreach outside of the test()
[
{ iconPosition: 'center', small: true, expectedResult: undefined },
{ iconPosition: 'center', small: false, expectedResult: undefined },
{ iconPosition: 'left', small: true, expectedResult: '10px 20px 10px 20px' },
{ iconPosition: 'left', small: false, expectedResult: '17px 42px 18px 42px' },
{ iconPosition: 'right', small: true, expectedResult: '10px 20px 10px 20px' },
{ iconPosition: 'right', small: false, expectedResult: '17px 42px 18px 42px' },
].forEach( ({iconPosition, small, expectedResult}) => {
test(`buttonPadding with params (${iconPosition}, ${small}) => ${expectedResult}`, function () {
expect(buttonPadding({ iconPosition, small })).toEqual(expectedResult);
});
});
By passing the names into the test log it can show what was passed in and what the result should be when it fails.
Upvotes: 0