对模拟函数的断言失败

Vishwa

我正在尝试使用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)
布赖恩·亚当斯

问题

Promise调用回调instance.handleResponse已经不是由时间运行mockHandleSearch.call(instance);的回报和expect运行。

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

在这种情况下,最简单的方法是使您的测试函数async,返回PromisefrommockHandleSearchawait返回Promise

it("handle search function", async () => {  // make the test function async

  ...

  const mockHandleSearch = jest.fn(postcode => {
    console.log("mockHandleSearch called");
    return getPostcodeDetails("abc").then(instance.handleResponse);  // return the Promise
  });
  instance.handleSearch = mockHandleSearch;
  await mockHandleSearch.call(instance);  // await the returned Promise
  expect(instance.handleResponse).toBeCalled();  // SUCCESS
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TOP 榜单

  1. 1

    来自Microsoft Office加载项taskpane.js的MySQL驱动程序模块的空引用

  2. 2

    使用AWS Cognito和React的仅限Facebook / Google的登录名(无用户名/密码)

  3. 3

    创建Windows Phone 8应用并将其连接到数据库的最佳方法(最好是SQL Server)

  4. 4

    为什么Java中的System.out.println()打印到控制台?

  5. 5

    卷曲函数无法解析来自bash中变量的代理

  6. 6

    是什么在Android的consumer-rules.pro和proguard-rules.pro之间的区别?

  7. 7

    设置与Apache POI Excel表散点图标记图标的颜色

  8. 8

    将Qt Pyside2与asyncio await语法一起使用?

  9. 9

    崇高的文字+蟒蛇的蟒蛇

  10. 10

    任务':app:minifyReleaseWithR8'.java.lang.NullPointerException的执行失败(无错误消息)

  11. 11

    OpenJDK的和AdoptOpenJDK的区别

  12. 12

    大型数据集缓存到Spark内存中时,“超出了GC开销限制”(通过sparklyr和RStudio)

  13. 13

    “执行测试CMAKE_HAVE_LIBC_PTHREAD”失败实际上是什么意思?

  14. 14

    使用Core 2.2中的Identity,如何在关闭浏览器15分钟后保持会话活动?

  15. 15

    React中的ForwardRefExoticComponent和ForwardRefRenderFunction有什么区别?

  16. 16

    猫鼬查找结果,然后将字段替换为findOne

  17. 17

    如何降级Google Colab的Torch版本

  18. 18

    Keras提前停止回调错误,val_loss指标不可用

  19. 19

    如何避免VSCode中的“导入路径不能以.ts扩展名结尾”错误?

  20. 20

    Nuxt.JS:如何在页面中获取路由URL参数

  21. 21

    是否有为什么会AccessibilityManager.sInstance导致内存泄漏的一个原因?

热门标签

归档