在使用 react-testing-library 进行测试期间,单击两次 material-ui 图标不会将其颜色更改为默认颜色

Clicking twice material-ui icon does not change its color to default during tests with react-testing-library

我有一个 material-ui 导航栏,上面有几个 material-ui 图标。其中之一是书签图标。单击该图标时,它变为蓝色 (rgb(25, 118, 210)),再次单击它或在页面某处单击时,它应变为白色。这是使用局部变量实现的。

 <Popover
     ...
     trigger={
       <IconButton classes={{ root: classes.topBarIconButton }}>
          <BookmarksIcon aria-label="bookmarks icon" className={classes.favoriteIcon} />
       </IconButton>
     }
     onEnter={() => setBookmarksOpen(true)}
     onClose={() => setBookmarksOpen(false)}
     >
     <BookmarksList pageTitle={pageTitle} />
 </Popover>

我想现在使用 react-testing-library 测试行为(点击按钮两次)。 我能够成功测试单击后图标变为蓝色。但是一旦再次点击,我就会继续收到蓝色,而不是预期的白色或 #fff 或 rgb 格式的颜色。

test('clicking bookmarks icon once becomes blue, clicking twice becomes white', () => {
      renderWithAllProviders(<Topbar {...props} />, reduxState);
    
      const bookmarksIcon = screen.getByLabelText('bookmarks icon');
      userEvent.click(bookmarksIcon);
      // bookmarks icon color becomes blue on click
      expect(bookmarksIcon).toHaveStyle({ color: 'rgb(25, 118, 210)' }); // this works as expected
      
      userEvent.click(bookmarksIcon);
      // bookmarks icon color becomes white on second click
      expect(bookmarksIcon).toHaveStyle({ color: 'white' }); // this does not work as expected
    
      // 2nd attempt
      // await waitFor(async () => {
      //   // const asyncBookmarksIcon = await screen.findByLabelText('bookmarks icon');
      //   expect(asyncBookmarksIcon).toHaveStyle({ color: 'white' });
      // });
 });

我收到以下错误:

● clicking bookmarks icon once becomes blue, clicking twice becomes white

expect(element).toHaveStyle()

- Expected

- color: white;
+ color: rgb(25, 118, 210);

我也尝试使用 waitFor 方法,但就其输出而言,错误变得更大:

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

包含第一个错误和带有打印 material ui(可能)原生 css 声明的大输出。

这里是demo的问题。 (更好的下载和 运行 它在本地会导致它由于某种原因冻结,尽管 运行 在本地工作正常)。

欢迎提出任何想法或建议。

我最终在官方 react-testing-library git 中心存储库中问了这个问题。

我从其中一位贡献者那里得到了以下答案。

You run your tests in JSDOM which has not full CSS support

这意味着只能测试部分 css 行为。

他提到:

Anything .toHaveStyle has a low confidence depending on how these styles are applied. You should use visual regression tests for these types of assertions.

您可以在此 link 中找到问题以获取更多信息。