首页 > 解决方案 > 预期的模拟函数被调用了一次,但它被调用了零次。如何解决?

问题描述

我使用 Enzyme 对 App 组件进行了 e2e 测试,但此测试出现下一条错误消息:

预期的模拟函数被调用了一次,但它被调用了零次。

是什么导致了问题?提前感谢您的帮助。

测试错误代码: https ://codesandbox.io/s/x348jx4qzw

测试代码:

import React from "react";
import Enzyme, { shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";

import App from "./app.js";
const movieTitlesCollection = [`Fantastic Beasts`];

Enzyme.configure({ adapter: new Adapter() });

describe(`AppComponent`, () => {
  it(`should simulate card title click`, () => {
    const handleClick = jest.fn();
    const wrapper = shallow(
      <App movieTitles={movieTitlesCollection} onClick={handleClick} />
    );
    const filmCardTitle = wrapper.find(`.small-movie-card__link`);

    expect(filmCardTitle.length).toEqual(1);
    filmCardTitle.simulate(`click`);
    expect(handleClick).toHaveBeenCalledTimes(1);
  });
});

标签: javascriptjestjsenzyme

解决方案


onClick 属性应提供给 App 组件中的 'small-movie-card__title;

const App = ({movieTitles, onClick}) => {
      const filmCard = movieTitles.map((movieTitle, index) =>
        <article className="small-movie-card catalog__movies-card" key={index}>
          <button className="small-movie-card__play-btn" type="button">Play</button>
          <div className="small-movie-card__image">
            <img src="img/fantastic-beasts-the-crimes-of-grindelwald.jpg" alt="Fantastic Beasts: The Crimes of Grindelwald" width="280" height="175"/>
          </div>
          <h3 className="small-movie-card__title">
            <a className="small-movie-card__link" href="movie-page.html" onClick={onClick}>
              { movieTitle }
            </a>
          </h3>
        </article>
      );

other code...

推荐阅读