Jest (React TypeScript): testing an internal component function: Error: Expected number of calls: >= 1 Received number of calls: 0

Jest (React TypeScript): testing an internal component function: Error: Expected number of calls: >= 1 Received number of calls: 0

我已经开始测试我的代码并希望确保在渲染组件时调用特定函数,这是我的 tsx 文件:

import logo from './logo.svg';
import './App.css';

interface testProps {
  isAuthenticated?: boolean;
}
function App(props: testProps) {
  const runFunction = () => console.log('Hello!');
  if (props.isAuthenticated) {
    runFunction();
  }
  return (
    <div className='App'>
      <header className='App-header'>
        <img src={logo} className='App-logo' alt='logo' />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className='App-link'
          href='https://reactjs.org'
          target='_blank'
          rel='noopener noreferrer'>
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

这是我写的测试:

import React from 'react';
import { render } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
  const runFunction = jest.fn();
  render(<App isAuthenticated={true} />);
  expect(runFunction).toHaveBeenCalled();
});

这将引发以下错误:

 Expected number of calls: >= 1
    Received number of calls:    0

你不能像在你的反应组件中定义的函数那样只命名一个模拟函数。

您可以将您的 runFunction 作为 prop 传递给该组件并查看它是否会被调用。 你也可以嘲笑 console.log 喜欢

global.console = {log: jest.fn()}

并测试其执行情况

expect(console.log).toHaveBeenCalledWith('Hello!')