1

给定 then 组件Menu.tsx

import React, { useState } from 'react';
import { Grid, Button, Menu, MenuItem } from '@material-ui/core';

const Component = () => {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  const handleMenuClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  return (
    <Grid>
      <Button variant="contained" onClick={handleMenuClick}>
        Open Menu
      </Button>
      <Menu
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        <MenuItem>Option 1</MenuItem>
        <MenuItem>Option 2</MenuItem>
      </Menu>
    </Grid>
  );
};

export default Component;

和快照测试Menu.test.tsx

import React from 'react';
import { create } from 'react-test-renderer';
import Menu from './Menu';

describe('Menu Snapshot', () => {
  it('renders correctly', () => {
    const tree = create(<Menu />).toJSON();
    expect(tree).toMatchSnapshot();
  });
});

运行测试给出错误TypeError: parentInstance.children.indexOf is not a function

谷歌搜索后,我尝试添加 createNodeMock 函数:

const tree = create(<Menu />, {
  createNodeMock: (element) => element,
}).toJSON();

这会产生错误Argument appears to not be a ReactComponent. Keys: type,props

不太了解幕后发生了什么,所以我发现的解决方法对我不起作用。测试这个的正确方法是什么?

链接到代码sanbox.io

4

0 回答 0