使用Jest spyOn测试库方法

时间:2018-08-03 02:32:04

标签: reactjs jestjs enzyme

在我的项目中有一个包含许多有用方法的util库,我想使用jest.spyOn来测试它们中的每一个。这是我的util.js库的一部分

import { connect } from "react-redux";
import { withRouter } from "react-router-dom";

import { compose } from "recompose";

export const withRouterAndConnect = (mapStateToProps, mapDispatchToProps) =>
  compose(
    withRouter,
    connect(
      mapStateToProps,
      mapDispatchToProps
    )
  );

export const applyShadow = dp => {
  if (dp === 0) {
    () => "none";
  } else {
    let shadow = "0px";
    const ambientY = dp;
    const ambientBlur = dp === 1 ? 3 : dp * 2;
    const ambientAlpha = (dp + 10 + dp / 9.38) / 100;

    shadow +=
      ambientY +
      "px " +
      ambientBlur +
      "px rgba(0, 0, 0, " +
      ambientAlpha +
      "), 0px";

    const directY = dp < 10 ? Math.floor(dp / 2) + 1 : dp - 4;
    const directBlur = dp === 1 ? 3 : dp * 2;
    const directAlpha = (24 - Math.round(dp / 10)) / 100;
    shadow +=
      directY + "px " + directBlur + "px rgba(0,0,0, " + directAlpha + ")";
    shadow => shadow;
  }
};

这是我的apply {shadow}方法的index.test.js文件

import React from "react";
import { configure, shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import toJson from "enzyme-to-json";

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

describe("mock function testing", () => {
  test("test spyOn", () => {
    const mockFn = jest.spyOn("./lib/util", "applyShadow");
    expect(mockFn(2)).toEqual('resultOutput');
  });
});

我使用create-react-app,当我键入npm rum test时,错误消息会在控制台中输出

TypeError: Cannot read property '_isMockFunction' of undefined

1 个答案:

答案 0 :(得分:1)

jest.spyOn期望对象是第一个参数,而给出了./lib/util字符串。监视您自称的方法没有道理。

应该将其测试为:

import * as util from "./lib/util";
...
expect(util.applyShadow(2)).toEqual(...);