您可以/如何将构造函数添加到对象中?

时间:2019-01-25 00:37:13

标签: javascript reactjs constructor enzyme

是否可以向对象添加构造函数?

如果可能的话,我想完成类似的事情:

const constructorObject = {
  Constructor: Constructor("content")
}

如果访问了该对象,则可以执行以下操作:

new constructorObject.constructor({ content: "content" }):

没有错误提示:

undefined is not a constructor 
(evaluating 'new constructorObject.Constructor({ content: "content })')

对于上下文,我有一个react组件,并且正在parent组件中调用googleAPI。

this.googleAPI被传递到child。 当我运行测试时-props被传递到child但对象中没有constructor时-测试失败。

childComponent中,initmount上被调用:

init() {
   const { position, map, title, icon } = this.props;
   this.marker = new this.props.googleApi.Marker({
     icon,
     position,
     map,
     title
   });
}

在酶测试中:

import React from "react";
import { shallow } from "enzyme";
import Child from "src/components/child";

describe("components/child", () => {
  let props;
  beforeEach(() => {
    props = {
      googleApi: {},
      map: {},
      position: {
        lat: 10,
        lng: 10
      },
      title: "title",
      icon: "icon"
    };
  });

  describe("on mount", () => {
    it("should render into the document", () => {
      const component = shallow(<Marker {...props} />);
      expect(component).to.not.be.null;
    });
  });
});

这是enzyme错误:

undefined is not a constructor (evaluating 'new this.props.googleApi.Marker({ title: this.props.title })')

2 个答案:

答案 0 :(得分:1)

通常会使用jest之类的东西来嘲笑外部资源。在这种情况下,我将假定为googleAPI

beforeEach中初始化道具时,

如果您想在addListener内添加一个Marker 是构造函数,我会尝试:

let props;
let component;
beforeEach(() => {
    props = {
      googleApi: {
        Marker: () => ({ addListener: jest.fn() })
      },
    };
    component = shallow(<Marker {...props} />);
});

如果您只需要一个功能,则可以执行以下操作:

props = {
      googleApi: {
        ChildComponent: () => ({ click: jest.fn() }),
        event: {
          addListener: jest.fn()
        }
      }
    }

https://jestjs.io/docs/en/mock-functions了解更多信息。

答案 1 :(得分:1)

在JS中,构造函数可以只是一个函数。参见this。基本上,这应该对您有用:

beforeEach(() => {
  props = {
    googleApi: {
      Marker: () => {}
    },
    map: {},
    position: {
      lat: 10,
      lng: 10
    },
    title: "title",
    icon: "icon"
  };
});