I have a component that has a child component.
This child component has some rules to display its children content, and I want to mock it to display the content regardless its rules.
import MediaQuery from './component.media.query'
class Dumb extends Component { render() {
return (
<Fragment>
<div>Generic content</div>
<MediaQuery device="DESKTOP">
<div id="desktop">Specific desktop content</div>
</MediaQuery>
</Fragment>
) } }
I've tried some ways, and even the simplest is not working:
describe('Dumb component', () => {
jest.doMock('./component.media.query', () => {
const Comp = () => <div id='desktop'>Mocked</div>
return Comp
})
it('should display the desktop', () => {
const wrapper = mount(<Dumb />)
expect(wrapper.find('#desktop')).toExist()
})
})
Any ideas?
In your test you can mock it like this :
jest.mock('./component.media.query', () => () => 'MediaQuery')
//note that you have to enter the path relative to the test file.
With enzyme you can find the element like this
wrapper.find('MediaQuery')
Related
I want to convert my class component to functional component and t is difficult for me to convert render() of class component.
Here is my code sandbox link. https://codesandbox.io/s/snowy-smoke-s65vx4?file=/src/App.js
Can anyone please help me with this
The render part is just going to be the body of the function and the return.
const myfunccomp : React.FC = ({id, info, msgList}) => {
const chatContentHeader = () => {...}
const chatContentBody = () => {...}
const chatContentFooter = () => {...}
...
return (
<div className="chat-content">
{chatContentHeader(info.name)}
{chatContentBody(msgList, id)}
{chatContentFooter()}
</div>
);
}
I'm trying to test a Parent component which has a method that has been called from Child component. An example:
Parent.js
export default function Parent() {
const methodToTest = () => {
//method code
}
return (
<div>
<Child onChange={methodToTest} />
</div>
)
}
Child.js
export default function Child({ onChange }) {
const handleChange = () => {
onChange()
}
//InaccesibleElement is a component from a library that not render the element in test instance.
return (
<div>
....
<InaccesibleElement onClick={() => handleChange()} />
</div>
)
}
I would thinking to mock Child and inject into Parent component but doesn't work or I don't know how to do it correctly. My test example:
Parent.test.js
function ChildMock({ onChange }) {
const handleChange = () => {
onChange("mockedValue");
}
return(
<button onClick={() => handleChange()}>click me</button>
)
}
jest.mock('../components/Child', () => {
return { Child: ChildMock}
})
test("test parent method", () => {
const component = render(<Parent />);
const button = component.getByText("click me");
//rest of the test...
})
jest.mock() throws an exception:
"Reference error: The module factory of jest.mock() is not allowed to reference any out-of-scope variables.
Invalid variable access: BarGraphContainerMock
Allowed objects: Array, ArrayBuffer, Atomics, BigInt, BigInt64Array, BigUint64Array, Boolean, Buffer, DataView, Date, ....
Note: This is a precaution to guard against uninitialized mock variables. If it is ensured that the mock is required lazily, variable names prefixed with mock (case insensitive) are permitted."
Thanks.
I'm using jest/enzyme and want to check existence child elements of React component
if i have function as component child
const children = () => (
<>
<div>...</div>
<div>...</div>
</>
)
return <Component>{children}</Component>;
why i can't do like this
test('Should render div', () => {
wrapper = shallow(<MyComponent />);
const component = wrapper.find(Component);
expect(component.exists()).toBe(true); //return true
const children = wrapper.find('div')
expect(children.exists()).toBe(false); //return false
});
Your children function is basically a render prop and shallow doesn't render it. You can however trigger the rendering by calling it as a function like
shallow(
shallow(<MyComponent />)
.find(Component)
.prop('children')()
)
So your test will look like
test('Should render div', () => {
wrapper = shallow(<MyComponent />);
const component = wrapper.find(Component);
expect(component.exists()).toBe(true); //return true
const renderProp = shallow(component.prop('children')());
const children = renderProp.find('div');
expect(children.exists()).toBe(true);
});
I'm new to react :)
If my component render looks like this:
render() {
return (
<object-search className="m-t-xs">
<div className="stats-title pull-left">
<h4>Object Search</h4>
and my tests are:
beforeEach(() => {
component = TestUtils.renderIntoDocument(<ObjectSearch {...props}/>);
renderedDOM = () => ReactDOM.findDOMNode(component);
});
it('should render with the correct DOM', () => {
const parent = renderedDOM();
expect(parent.tagName).toBe('OBJECT-SEARCH');
expect(parent.children.length).toBe(7);
expect(parent.classList[0]).toEqual('m-t-xs');
})
why am I seeing an empty classList attribute?
Home page ObjectSearch Rendering of ObjectSearch on componentDidMount should render with the correct DOM FAILED
Expected '' to equal 'm-t-xs'.
Note: using the karma test runner and jasmine
Just want to implement the unit test for my react component with using the Jest and Enzyme.
Is there a way to test the order? Let's say I have component Button, and I want to render icon and text at the same time.
And of course it's good to provide the alignment option to the user(Icon first or Children first).
Button.js
class Button extends React.Component {
constructor() {
super();
}
render() {
let content;
const icon = (<Icon type='search' />);
if (this.props.iconAlign === 'right') {
content = (<span>{this.props.children} {icon}</span>
} else {
content = (<span>{icon} {this.props.children}</span>
}
return (
<button>{content}</button>
);
}
}
How to test the iconAlign props with Jest and Enzyme?
Check on the type of the component
Check icon first
var button = TestUtils.renderIntoDocument(<Button />);
var buttonNode = ReactDOM.findDOMNode(button);
expect(buttonNode.props.children[0].type.name).toEqual("Icon")
You could use a shallow render and compare the output. I am not familiar with the Jest syntax so that side of my example may be incorrect (I quickly referred to their website):
import { shallow } from 'enzyme';
describe(`Button`, () => {
it(`should render the icon on the right`, () => {
const children = <div>foo</div>;
const actual = shallow(
<Button iconAlign="right" children={children} />
);
const expected = (
<button><span>{children} <Icon type='search' /></span></button>
);
expect(actual.matchesElement(expected)).toBeTruthy();
});
});
And then you could create another test for the "left" align.
The enzyme version of #pshoukry's answer.
describe(`Button`, () => {
it(`should render icon on the right`, () => {
const wrapper = shallow(
<Button iconAlign="right">
<div>foo</div>
</Button>
);
const iconIsOnRight = wrapper.find('span').childAt(1).is(Icon);
expect(iconIsOnRight).toBeTruthy();
});
});
For reference, here is the enzyme shallow rendering API documentation: https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md