预期模拟函数已被调用一次,但被调用了零次。如何解决?

时间:2019-05-04 14:07:17

标签: javascript jestjs 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);
  });
});

1 个答案:

答案 0 :(得分:0)

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...