在jest测试中,避免根据特定条件来调用expect
语句,因为这会使代码难以维护和理解。相反,使用条件语句包装测试结构,或编写不同的测试用例来覆盖不同的情况。
例如,考虑以下代码片段:
test('should render warning message if user is not logged in', () => {
const isLoggedIn = false;
const wrapper = shallow( );
if(!isLoggedIn) {
expect(wrapper.find('.warning-message')).toHaveLength(1);
}
});
请注意,在这个测试用例中,expect
语句被一个条件语句包装起来,以便只有在isLoggedIn
为false
时才运行。这样做可能会导致测试失败,因为如果isLoggedIn
变成true
,该测试用例将会失败,但测试不会指出哪一行出现了问题。
为了避免这种情况,我们可以编写两个不同的测试用例,一个测试当用户已经登录,另一个测试当用户未登录的情况。
例如:
describe('When user is logged in', () => {
test('should render component without warning message', () => {
const isLoggedIn = true;
const wrapper = shallow( );
expect(wrapper.find('.warning-message')).toHaveLength(0);
});
});
describe('When user is not logged in', () => {
test('should render warning message', () => {
const isLoggedIn = false;
const wrapper = shallow( );
expect(wrapper.find('.warning-message')).toHaveLength(1);
});
});
这样做不仅使测试更具可读性,而且使代码更易于维护,因为每个测试用例都独立于其他测试用例。