簡體   English   中英

酶和反應路由器:如何使用 useHistory 淺渲染組件

[英]Enzyme & React router: How to shallow render a component with useHistory

我一直在嘗試的是用shallow渲染組件,這是由enzyme提供的。

該組件正在使用react-router-dom useHistory

const baseMatch: match<{ id: string }> = { /* path, url, params */};
const location = createLocation(baseMatch.url);

describe('MyComponent', () => {
  const baseProps = {
    history: createMemoryHistory(),
    location: createLocation(baseMatch.url),
    match: baseMatch
  };

  beforeEach(() => {
    jest.mock('react-router-dom', () => ({
      useHistory: jest.fn()
    }));
  });

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

  it('renders blah blah', () => {
    const wrapper = shallow(<MyComponent {...baseProps} />);
    // testing MyComponent here...
  });

我參考了這篇文章,並以同樣的方式放置了jest.mock

但是,這會導致TypeError: Cannot read property 'history' of undefined

控制台說:

MyComponent › renders blah blah

    TypeError: Cannot read property 'history' of undefined

      24 | const MyComponent = (props: IProps) => {
      25 |   console.log('useHistory', useHistory);
    > 26 |   let history = useHistory();

奇怪的是,上面第 25 行的console.log打印了useHistory的實現(換句話說,它不是未定義的)。

顯然, useHistory沒有被嘲笑。 我懷疑不能用shallow來嘲笑useHistory (在上面的帖子中,海報使用的是mount() )。

但是,我不是 100% 確定,因為我無法從enzymereact-router的文檔中找到shallow是否與useHistory兼容。

是否可以在useHistory使用shallow 任何建議將被認真考慮。

文檔

注意:為了正確模擬,Jest 需要 jest.mock('moduleName') 與 require/import 語句在同一范圍內。

因此,不要在beforeEachbeforeEach react-router-dom - 嘗試將其置於頂級范圍:

jest.mock('react-router-dom', () => ({
  useHistory: jest.fn()
}));

const baseMatch: match<{ id: string }> = { /* path, url, params */};
const location = createLocation(baseMatch.url);


describe('MyComponent', () => {
  const baseProps = {
    history: createMemoryHistory(),
    location: createLocation(baseMatch.url),
    match: baseMatch
  };

...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM