我想知道哪种方法更好。我是否可以在测试中使用if
条件,或者当有这种情况时,最好将它们分成两个.each
测试?
test.each([['Option 1'], ['Option 2']])(
`WHEN selected %s option THEN parameters section is visible`,
async (optionName) => {
const { collectButton } = await initializeTest();
fireEvent.click(screen.getByText(optionName));
await expectElementToHaveAttribute(collectButton, 'disabled');
expect(screen.getByText(parametersSectionHeader)).toBeTruthy();
},
);
test.each([['Option a']])(
`WHEN selected %s option THEN parameters section is NOT visible`,
async (optionName) => {
const { collectButton } = await initializeTest();
fireEvent.click(screen.getByText(optionName));
await expectElementNotToHaveAttribute(collectButton, 'disabled');
expect(screen.queryByText(parametersSectionHeader)).toBeFalsy();
},
);
test.each([['Option 1', 'visible'], ['Option 2', 'visible'], ['Option a', 'NOT visible']])(
`WHEN selected %s option THEN parameters section is %s`,
async (optionName, visibility) => {
const { collectButton } = await initializeTest();
fireEvent.click(screen.getByText(optionName));
if(visibility === 'visible') {
await expectElementToHaveAttribute(collectButton, 'disabled');
expect(screen.getByText(parametersSectionHeader)).toBeTruthy();
} else {
await expectElementNotToHaveAttribute(collectButton, 'disabled');
expect(screen.queryByText(parametersSectionHeader)).toBeFalsy();
}
},
);
当涉及到if
时,它们应该是不同的测试,明确性是测试中的首选,更不用说使其成为单一测试并不会使其变得更加干燥。如果某些部分是可重用的,可以将其提取到辅助函数中。
在这种情况下,可以通过不使用特定于测试的断言来解决:
test.each([['Option 1', true], ['Option 2', false], /*...*/])(
`WHEN selected %s option THEN parameters section is %s`,
async (optionName, visibility) => {
const { collectButton } = await initializeTest();
fireEvent.click(screen.getByText(optionName));
await expectElementToHaveAttribute(collectButton, 'disabled');
expect(Boolean(screen.getByText(parametersSectionHeader))).toBe(visibility);
},
);