对模拟函数的断言失败

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 条评论
登录 后参与评论

相关文章

Python pytest模拟失败,对函数调用断言“置为无”

在模拟的导入类上,称为断言的函数失败

Python模拟失败的调用断言

对函数指针的断言失败

匿名Javascript函数断言失败

即使调用了模拟,Python 模拟断言也会失败

Python - 模拟函数和断言异常

响应模拟 requests.ConnectionError,断言函数

golang 测试断言函数的 nil 返回失败

函数'contourArea'中的OpenCV(4.0.0)断言失败

断言失败时的Python unittest调用函数

由CreateDC()函数引起的调试断言失败

Flutter 断言在调用函数时失败

Mokito无法模拟方法并且断言总是失败

传递正确的 args 时,证明模拟失败的断言

调用 FakeItEasy 模拟 mediatr.send 方法失败断言

断言断言失败

断言在python中用json字符串调用的模拟函数

如何断言使用生成器调用了模拟函数?

如何使用 jest 在模拟函数中断言类的属性

开玩笑-断言异步函数引发测试失败

加载图像在函数cv :: inRange中返回断言失败

访问DLL中的函数时出现调试断言失败错误

Bitwise_and函数返回错误断言失败并且掩码相同

CV4.1:函数detectAndCompute级别中的断言失败>=0

在摩卡中,断言函数中的“断言”导致超时而不是失败

MIMEMessage 和 MIMEMessage 模拟测试用例因 EmailUtil 上的断言错误而失败

称为断言的函数如何断言

\ resize.cpp:3787:错误:(-215:断言失败)函数!= 0在函数'cv :: hal :: resize'中