开玩笑测试在条件渲染上失败

时间:2020-10-27 13:47:57

标签: reactjs jestjs create-react-app enzyme

我有一个React组件MainPage,其状态称为“通知”。在此React组件内,根据通知状态有条件地呈现子Notification组件。我正在使用Jest来测试,当没有通知时,子组件不存在。但是当有通知时,它就存在。

这是我的组件中要进行条件渲染的块:

{
    notifications.length > 0 ? <NotificationCircle data-test="component-notification-circle" className="NotificationCircle">
         {
            notifications?.length >= 10 ? '10+' : notifications.length
         }
 </NotificationCircle> : ''
}


状态被初始化为[],并填充在useEffect内

const [notifications, setNotifications] = React.useState<any>([]);

这是我的测试文件中的设置:

const initialState = { user: { userData: [],  users: { users: []}} };

const setup = (state = {}) => {

    const wrapper = shallow(<MainPage />);
    return wrapper;
}

和我的测试:

describe('notification circle component', () => {
    let wrapper: any;
    let mockSetNotifications = jest.fn();

    beforeEach(() => {
        mockSetNotifications.mockClear();
        wrapper = setup(initialState).dive();
    })

    afterEach(() => {
        jest.clearAllMocks();
        jest.restoreAllMocks();
    })

    test('does not render when user has 0 notifications', () => {
   
        const notificationCircleComponent = testUtils.findByTestAttr(wrapper, 'component-notification-circle');

        expect(notificationCircleComponent.exists()).toBe(false);
    });

    test('renders when user has 1 or more notifications', () => {

        const mockNotifications = [{ notification_type_id: '1' }, { notification_type_id: '2' }];
        React.useState = jest.fn(() => [mockNotifications, mockSetNotifications]);
        
        mockSetNotifications(mockNotifications);
      
        const notificationCircleComponent = testUtils.findByTestAttr(wrapper, 'component-notification-circle');
        expect(notificationCircleComponent.exists()).toBe(true);
    });    
});


第一个测试通过(该测试可确保在没有通知的情况下不会呈现)。 第二项测试(在有通知时测试其存在)失败

任何人都可以帮助说明为什么第二个测试用例失败了吗?

0 个答案:

没有答案