对模拟函数的断言失败

时间:2018-11-28 15:33:16

标签: reactjs jestjs enzyme

我正在尝试使用Jest和Enzyme测试反应组件。

当我断言是否使用Jest的 .toBeCalled()调用了函数时,测试失败。我尝试通过 console.log()跟踪代码,我可以看到所有模拟都在被调用,但是断言失败了。

我花了很多时间尝试研究Just,Enzyme文档和Stackoverflow,但无法弄清楚我在做什么错。

如果我做错了事,请让我吗?这是我的下面的代码

Postcode.js

   
import React, { Component } from "react";
import getPostcodeDetails from "../services/PostcodeService";
import SearchBox from "../components/searchbox/SearchBox";

let initialState = {
  statusOK: 0,
  postcode: "",
  error: ""
};

class Postcode extends Component {
  constructor(props) {
    super(props);
    this.state = initialState;
    this.handleSearch = this.handleSearch.bind(this);
    this.result = "";
    this.handleResponse = this.handleResponse.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  handleResponse(response) {
    //some code
  }

  handleError(err) {
    //some code
  }

  handleSearch(postcode) {
    getPostcodeDetails(postcode)
      .then(this.handleResponse)
      .catch(this.handleError);
  }

  render() {
    return (
      <div>
        <SearchBox handleSearch={this.handleSearch} />
      </div>
    );
  }
}

export default Postcode;

Postcode.test.js

   
import React from "react";
import { shallow } from "enzyme";
import Postcode from "./Postcode";
import getPostcodeDetails from "../services/PostcodeService";

jest.mock("../services/PostcodeService");

it("handle search function", () => {
  const wrapper = shallow(<Postcode />);
  const instance = wrapper.instance();
  const mockHandleResp = jest.fn(() => {
    console.log("Handle resp moc-");
  });
  instance.handleResponse = mockHandleResp;

  //This is a async function in a module.
  getPostcodeDetails.mockImplementation(postcode => {
    return new Promise((resolve, reject) => {
      if (postcode === "abc") {
        console.log("Resolving");
        console.log(jest.isMockFunction(resolve));
        resolve();
      } else {
        console.log("Rejecting");
        reject();
      }
    });
  });

  const mockHandleSearch = jest.fn(postcode => {
    console.log("mockHandleSearch called");
    getPostcodeDetails("abc").then(instance.handleResponse);
  });
  instance.handleSearch = mockHandleSearch;
  mockHandleSearch.call(instance);
  expect(instance.handleResponse).toBeCalled();
});

控制台输出

   
    Console
    console.log src/containers/abc.test.js:32
      mockHandleSearch called
    console.log src/containers/abc.test.js:21
      Resolving
    console.log src/containers/abc.test.js:22
      false
    console.log src/containers/abc.test.js:34
      Promise { undefined }
    console.log src/containers/abc.test.js:13
      Handle resp moc-

  ● <Postcode> › handle search function

    expect(jest.fn()).toBeCalled()

    Expected mock function to have been called, but it was not called.

      37 |     instance.handleSearch = mockHandleSearch;
      38 |     mockHandleSearch.call(instance);
    > 39 |     expect(instance.handleResponse).toBeCalled();
         |                                     ^
      40 |   });
      41 | });
      42 |

      at Object.toBeCalled (src/containers/abc.test.js:39:37)

1 个答案:

答案 0 :(得分:1)

问题

Promise返回并运行instance.handleResponse时,调用mockHandleSearch.call(instance);的{​​{1}}回调尚未运行。

解决方案

在运行expect之前,请确保Promise回调有机会完成。

在这种情况下,最简单的方法是使测试功能expect,从async返回Promise,然后mockHandleSearch返回返回的{{1} }:

await