Say I have the following component:
export class ExampleComponent extends Component {
exampleMethod1 = () => {
console.log('in example 1')
}
exampleMethod2 = () => {
console.log('in example 2')
this.exampleMethod1()
}
render() {
return (
<TouchableOpacity id='touchable' onPress={exampleMethod2}><Text>Touchable</Text></TouchableOpacity>
)
}
}
This works exactly how you would expect. The button appears, and can be pressed. Both methods fire, and console log their text.
I now try to test this with jest:
describe('example tests', () => {
let wrapper
beforeEach(() => {
wrapper = shallow(<ExampleComponent/>)
})
it('this test fails. Interestingly both messages still print', () => {
const instance = wrapper.instance()
instance.exampleMethod2 = jest.fn()
wrapper.find('#touchable').simulate('press')
//wrapper.update() uncommenting this line has no effect.
expect(instance.exampleMethod2.mock.calls.length).toBe(1)
})
it('this test passes. Only the first message prints', () => {
const instance = wrapper.instnace()
instance.exampleMethod1 = jest.fn()
wrapper.find('#touchable').simulate('press')
expect(instance.exampleMethod1.mock.calls.length).toBe(1)
})
})
As annotated, the first test fails, and the original message prints, as if I had never mocked out the method. This happens irrespectively of whether wrapper.update() is run or not.
Interestingly, if we replace the onPress with a seemingly identical arrow function like so:
onPress={() => {exampleMethod2()}}
The test suddenly passes. This whole thing suggest some weird this binding shenanigans (I think?). Any explanation as to what is going on would be much appreciated!
If you want to test custom methods on component's prototype object, you should use mount function from enzyme and use spyOn to mock and trace the call to that method.
export class ExampleComponent extends Component {
exampleMethod1 = () => {
console.log('in example 1');
this.setState({ example1: true });
}
exampleMethod2 = () => {
console.log('in example 2')
this.exampleMethod1()
}
render() {
return (
<TouchableOpacity id='touchable' onPress={exampleMethod2}><Text>Touchable</Text></TouchableOpacity>
)
}
}
describe('example tests', () => {
let wrapper
beforeEach(() => {
wrapper = mount(<ExampleComponent/>)
})
afterAll(() => { wrapper = null; })
it('some desc here', () => {
const instance = wrapper.instance();
spyOn(instance, 'exampleMethod1').and.callThrough();
expect(instance.setState).toHaveBeenCalled();
});
})
Related
I have the following react hook which brings focus to a given ref and on unmount returns the focus to the previously focused element.
export default function useFocusOnElement(elementRef: React.RefObject<HTMLHeadingElement>) {
const documentExists = typeof document !== 'undefined';
const [previouslyFocusedEl] = useState(documentExists && (document.activeElement as HTMLElement));
useEffect(() => {
if (documentExists) {
elementRef.current?.focus();
}
return () => {
if (previouslyFocusedEl) {
previouslyFocusedEl?.focus();
}
};
}, []);
}
Here is the test I wrote for it.
/**
* #jest-environment jsdom
*/
describe('useFocusOnElement', () => {
let ref: React.RefObject<HTMLDivElement>;
let focusMock: jest.SpyInstance;
beforeEach(() => {
ref = { current: document.createElement('div') } as React.RefObject<HTMLDivElement>;
focusMock = jest.spyOn(ref.current as HTMLDivElement, 'focus');
});
it('will call focus on passed ref after mount ', () => {
expect(focusMock).not.toHaveBeenCalled();
renderHook(() => useFocusOnElement(ref));
expect(focusMock).toHaveBeenCalled();
});
});
I would like to also test for the case where document is undefined as we also do SSR. In the hook I am checking for the existence of document and I would like to test for both cases.
JSDOM included document so I feel I'd need to remove it and some how catch an error in my test?
First of all, to simulate document as undefined, you should mock it like:
jest
.spyOn(global as any, 'document', 'get')
.mockImplementationOnce(() => undefined);
But to this work in your test, you will need to set spyOn inside renderHook because looks like it also makes use of document internally, and if you set spyOn before it, you will get an error.
Working test example:
it('will NOT call focus on passed ref after mount', () => {
expect(focusMock).not.toHaveBeenCalled();
renderHook(() => {
jest
.spyOn(global as any, 'document', 'get')
.mockImplementationOnce(() => undefined);
useFocusOnElement(ref);
});
expect(focusMock).not.toHaveBeenCalled();
});
You should be able to do this by creating a second test file with a node environment:
/**
* #jest-environment node
*/
describe('useFocusOnElement server-side', () => {
...
});
I ended up using wrapWithGlobal and wrapWithOverride from https://github.com/airbnb/jest-wrap.
describe('useFocusOnElement', () => {
let ref: React.RefObject<HTMLDivElement>;
let focusMock: jest.SpyInstance;
let activeElMock: unknown;
let activeEl: HTMLDivElement;
beforeEach(() => {
const { window } = new JSDOM();
global.document = window.document;
activeEl = document.createElement('div');
ref = { current: document.createElement('div') };
focusMock = jest.spyOn(ref.current as HTMLDivElement, 'focus');
activeElMock = jest.spyOn(activeEl, 'focus');
});
wrapWithOverride(
() => document,
'activeElement',
() => activeEl,
);
describe('when document present', () => {
it('will focus on passed ref after mount and will focus on previously active element on unmount', () => {
const hook = renderHook(() => useFocusOnElement(ref));
expect(focusMock).toHaveBeenCalled();
hook.unmount();
expect(activeElMock).toHaveBeenCalled();
});
});
describe('when no document present', () => {
wrapWithGlobal('document', () => undefined);
it('will not call focus on passed ref after mount nor on previously active element on unmount', () => {
const hook = renderHook(() => useFocusOnElement(ref));
expect(focusMock).not.toHaveBeenCalled();
hook.unmount();
expect(activeElMock).not.toHaveBeenCalled();
});
});
});
I'm using react-intersection-observer in this component, when this element is inView, doSomething will be called. It is expected to trigger doSomething every time this element is seen by the user.
const Component = () => {
const { ref, inView } = useInView();
useEffect(() => {
if(inView) {
doSomething();
}
}, [inView])
return (
<div ref={ref}></div>
);
};
This works as expected, however, I don't know how to properly write this test case.
(useInView as jest.Mock).mockImplementation(() => ({inView: true}));
render(<Component />);
expect(doSomething).toHaveBeenCalledTimes(1); // Test passed
(useInView as jest.Mock).mockImplementation(() => ({inView: false}));
(useInView as jest.Mock).mockImplementation(() => ({inView: true}));
expect(doSomething).toHaveBeenCalledTimes(2); // Test failed
I am new to Jestjs and enzyme framework and I am trying to write test cases for a particular react component and I am little stuck.
export class ProductDetailsForm extends Component{
handleMetaDataDefinition = e => {
const { value, name } = e.target;
if (name === "xmlVersion") {
this.checkSpecialCharacters(value);
}
this.setState(prevState => ({
...prevState,
[name]: value
}));
this.props.setProductDetailsFormValue({
...this.props.productDetailsForm,
[name]: value
});
};
checkSpecialCharacters = value => {
if (!value || value.match(/^[a-zA-Z0-9._-]+$/)) {
this.setState(() => ({ error: '' }));
} else {
this.setState(() => ({
error: `Special characters and operators such as !##$%^&*()+{}:;?|\\[]'"= are not allowed`
}));
}
}
render(){
return(
<div>
<MetaDataDefinition
readOnly={false}
metaData={this.state}
handleMetaDataDefinition={this.handleMetaDataDefinition}
validateVersion={this.validateVersion}
/>
</div>
);
}
}
I have started with the test case, but I am stuck and unable to proceed how to work on the function handleMetaDataDefinition for full coverage including the function checkSpecialCharacters. Below is the code that I started to write for ProductDetailsForm.test.js
let wrapper;
beforeEach(() => {
wrapper = shallow(
<ProductDetailForm />
);
});
test("should call handleMetaDataDefinition", ()=> {
wrapper.find('MetaDataDefinition').props('handleMetaDataDefinition');
});
I have used some part of my actual code and not the whole code, as I need help in this specific part only to write test case for handleMetaDataDefinition and checkSpecialCharacters methods.
There're two possible option how to write your tests.
You can trigger validation from your MetaDataDefinition component and pass there needed data.
test("should call handleMetaDataDefinition", ()=> {
const component = wrapper.find('MetaDataDefinition');
fillYourComponentSomehow();
triggerAnEventSomehow();
/*For example component.find('button').simulate('click');
wrapper.update();// We can wait for updating state differently(if needed i'll take a look to doc.)
expect(wrapper.state()).toBe(stateThatYouExpect);
});
Or you can test it as 'black box'
test("should call handleMetaDataDefinition", ()=> {
const component = wrapper.find('MetaDataDefinition');
component.props().handleMetaDataDefinition(objectForMethod)
wrapper.update();
expect(wrapper.state()).toBe(stateThatYouExpect);
});
If you have HOCs around your component you'll need to find this component by class name
wrapper.find('ProductDetailsForm')
UPDATE
You can test it like
let wrapper;
let setProductDetailsFormValue;
beforeEach(() => {
setProductDetailsFormValue = jest.fn();
wrapper = shallow(
<ProductDetailForm setProductDetailsFormValue={setProductDetailsFormValue} />
);
});
test("should call handleMetaDataDefinition", ()=> {
const testObject = { target: {name: 'xmlVersion', value: '!!!123asd!'}, }
const component = wrapper.find('MetaDataDefinition');
component.props().handleMetaDataDefinition(testObject)
wrapper.update();
expect(wrapper.state().error).toBe('Special characters and operators such as !##$%^&*()+{}:;?|\\[]'"= are not allowed');
expect(wrapper.state()[xmlVersion]).toBe('!!!123asd!');
expect(setProductDetailsFormValue).toBeCalledWith({
[xmlVersion]: '!!!123asd!',
...other fields})
});
I have situation in my unit test case for a react application, where in a function calls for another function received in props from parent component. The parent component functions definition is something like this:
onSavePropClick(action) {
const save = this.saveProperty(action);
if(action === SAVE){
return () => new Promise(() => {
resolve(this.calculate().then(save));
});
}
return save;
}
This function call has been passed as props to the child component as
<MyComponent finalSave={this.onSavePropClick(SAVE)} onClose={()=>this.setState({closeWindow: true})} />
MyComponent has a function:
savingAndShowResults() {
const { finalSave, onClose } = this.props;
finalSave().then(() => {
onClose();
});
return true;
}
Now when I have a test for the executed, it throws me error as “Cannot read property then of undefined”, the test is as follows
const initialProps={
finalSave: jest.fn(),
onClose: jest.fn()
};
it(‘should handle saving and show results’, () => {
const component = shallow(
<MyComponent {...initialProps} />
);
component.instance().savingAndShowResults();
expect(initialProps.finalSave).toHaveBeenCalled();
expect(initialProps.onClose).toHaveBeenCalled();
});
I am not able to figure out why even on resolving in return in promise of Parent component’s function, gives me this error.
Please suggest.
Assuming initialProps.finalSave is a mock function, you need to make sure you're returning a promise from initialProps.finalSave:
const initialProps = {
finalSave: jest.fn().mockImplementation(() => Promise.resolve());
...
};
Good afternoon,
I have a component file structured like that globally :
class Component ...
render(){
const {array} = this.props
{!array.includes(value) ?
(<View ...props
id="myComponent"/>
....
</View>) :
(<View ...props
id="myOtherComponent"/>
....
</View>)
}
}
And in my test file, i'm doing the stuff like that :
describe('Testing Component', () => {
test('conditional rendering', () => {
const wrapper = shallow(<Component array={[value]}/>);
expect(wrapper.find(n => n.prop('id') === "myOtherComponent").exists(true))
});
});
But even if I modify the props sent for the array, it always returned me true... What's the keyword to check that the nested component is actually verified and rendered...
I think the error is in your expect argument.
I would use the findWhere function instead of find;
The exists method should not receive a parameter in this
case, as it only receives Enzyme's Selectors and not booleans (you can read more about it here);
Add a toBeTruthy call to the expect line.
Here's a similar situation to yours that we have a test for and it works just fine:
it('tests name', () => {
const mockComponent = shallow(<Component {...props} />);
const textNode = mockComponent.findWhere(n => n.text() === props.name);
expect(textNode.exists()).toBeTruthy();
});
So your test would end up looking like this:
describe('Testing Component', () => {
test('conditional rendering', () => {
const wrapper = shallow(<Component array={[value]}/>);
const node = wrapper.findWhere(n => n.prop('id') === 'myOtherComponent');
expect(node.exists()).toBeTruthy();
});
});