Is it possible to add a constructor to an object?
If the following were possible, I would like to accomplish something like:
const constructorObject = {
Constructor: Constructor("content")
}
If this object were accessed you would be able to do the following:
new constructorObject.constructor({ content: "content" }):
without getting an error saying:
undefined is not a constructor
(evaluating 'new constructorObject.Constructor({ content: "content })')
For context, I have a react
component, and I'm making a call to the googleAPI in a parent
component.
this.googleAPI
is passed to the child
. When I'm running the test - props
are passed to the child
but without a constructor
in the object - the test fails.
In the childComponent
the init
is called on mount
:
init() {
const { position, map, title, icon } = this.props;
this.marker = new this.props.googleApi.Marker({
icon,
position,
map,
title
});
}
In the Enzyme test:
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;
});
});
});
This is the enzyme
error:
undefined is not a constructor (evaluating 'new this.props.googleApi.Marker({ title: this.props.title })')
One would usually mock the external resources using something like jest . in this case i would assume that would be googleAPI
.
When initializing props in beforeEach
,
if you want to add an addListener
that is a constructor within your Marker
I would try :
let props;
let component;
beforeEach(() => {
props = {
googleApi: {
Marker: () => ({ addListener: jest.fn() })
},
};
component = shallow(<Marker {...props} />);
});
If you just need a function you can do:
props = {
googleApi: {
ChildComponent: () => ({ click: jest.fn() }),
event: {
addListener: jest.fn()
}
}
}
https://jestjs.io/docs/en/mock-functions for more info.
In JS a constructor can be just a function. See this . Basically this should work for you:
beforeEach(() => {
props = {
googleApi: {
Marker: () => {}
},
map: {},
position: {
lat: 10,
lng: 10
},
title: "title",
icon: "icon"
};
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.