score:5
your validatebeforesave
function is declared within somecomponent
making it a closed/private scope function not accessible outside. you can pass that function as a prop and you can then create spy and pass it as a prop value in your test and test for if the prop function passed (spy) was called or not
so you would modify your function somewhat like this:
// some validator function
function validatebeforesave(){
...
}
// some function component
const somecomponent = (props: imycomponentprops) => {
const { classes, validatebeforesave } = props;
// component has state
const [count, setcount] = usestate(0);
function handleclick() {
validatebeforesave();
.
.
.
}
return (
<div>
<button>
classname="savebtn"
onclick={handleclick}
</button>
</div>
);
};
and in your unit test, something like this:
// unit test
describe('somecomponent' () => {
it('validates model on button click', () => {
const validatespy = jest.fn();
const wrapper = mount(
<muithemeprovider theme={theme}>
<somecomponent validatespy={validatespy}/>
</muithemeprovider>,
);
const instance = wrapper.instance();
wrapper
.find('.savebtn')
.at(0)
.simulate('click');
expect(validatespy).tohavebeencalledtimes(1);
});
}
score:0
i had similar problem mocking callback prop method with react 16.x.x, enzyme instance method returns null, what you can do is pass directly jest.fn() as a prop.
example:
it('should invoke callback with proper data upon checkbox click', () => {
const spycheckboxclick = jest.fn((id, item) => ({
id,
item,
}))
const component: any = enzyme.mount(
<sectioncolumn {...{
...mockprops,
oncheckboxclick: spycheckboxclick,
}} />
);
expect(spycheckboxclick).tohavebeencalledtimes(0);
// perform click to checkbox
const checkboxcomponent = component.find('styledcheckbox');
const input = checkboxcomponent.first().children();
input.simulate('change');
expect(spycheckboxclick).tohavebeencalledtimes(1);
expect(spycheckboxclick()).toequal(null)
});
score:1
i was also facing the same issue - i did like below -
import * as react from 'react';
const samplecomponent = () => {
const samplemethod = () => {
console.log('hello world');
};
return <button onclick={samplemethod} type="button">click me</button>;
};
export default samplecomponent;
test -
import react from 'react';
import samplecomponent from './';
import { shallow } from 'enzyme';
describe('samplecomponent', () => {
test('should handle click correctly', () => {
const logspy = jest.spyon(console, 'log');
const wrapper = shallow(<samplecomponent></samplecomponent>);
const button = wrapper.find('button');
expect(button.text()).tobe('click me');
button.simulate('click');
expect(logspy).tobecalledwith('hello world');
});
});
we can spy on console.log, to assert it is to be called or not
Source: stackoverflow.com
Related Query
- How to use jest.spyOn with React function component using Typescript
- How to test with jest and typescript with types a basic react function component
- How to use forwardRef with FunctionComponent in React Native using TypeScript
- How do you correctly use React.lazy() in Typescript to import a react component with a generic type parameter?
- Is it possible to type a React function component with TypeScript without using arrow functions?
- Mocking simple internal function using Jest for use in rendered React component
- How to use Jest for testing a react component with localStorage?
- How to mock properly with Jest a React component using render props
- How to test a function inside React functional component using jest.spyOn with React Testing Library
- How to properly use TypeScript types with a Styled Component canvas on React
- how can my call the action in my component using typescript with react redux?
- How to fix "TypeError: Object(...) is not a function" when using a wrap function on React Component to authenticate user login with Browser Router
- Using React Jest Enzyme - How to pass a constructor object to my component with Shallow?
- How to use a state value with map function to display repeat ui in react component
- How to test a React Component with Props in TypeScript using Jest?
- How to call a function from different component using React with Redux Form?
- How to use Facebook Javascript SDK to login and force re-authentication with React Web and Typescript inside of a component
- How to test React component with children using jest and enzyme?
- How to Use Next.Js "Link" element as a custom React component with Typescript
- How to test if state of a component is changed by the function using jest and Enzyme in React TDD
- Using use-State hook in react function always throws an error + How to share a variable with another component
- How to test a function call after state receive value inside expression in React function component using Jest
- How can i test with jest a react component who use context api?
- How to use refs in React with Typescript
- How to use children with React Stateless Functional Component in TypeScript?
- How to mock React component methods with jest and enzyme
- Testing React Functional Component with Hooks using Jest
- How to mock history.push with the new React Router Hooks using Jest
- Using Jest to mock a React component with props
- How do I get an attribute of an element nested in a React component using Jest and/or Enzyme?
More Query from same tag
- Prevent sorting from styling column on antd
- Redirect does not redirect to home page instead redirects to setup page with redux
- React Router won't render pushed page after first navigation
- Rendering array from Axios server on reactjs
- How to save an image and download it in ReactJS?
- React router default route not working with nested structure
- How to use react-toastr?
- Issue with dictionary in React
- How to integrate constants and functions in React Component class?
- React setState to push all items in array to state
- how to run 1 Express server project multiple time and with diferent .env file
- Youtube video in html (detect if the video was played)
- Is there a way to add a class to all elements that has a property set to true?
- Is there any way share state between
- Gatsby: how to pass data to React Context at build time
- Typescript module resolution fails despite "main" property set in package.json
- React Build Hosting in Apache: Forbidden error
- change style of row in react big calendar
- Good way to chain or combine multiple "patchers"?
- index isn't working as expected in React array.Map function
- How to save response to localStore with Redux Thunk?
- React render modal in list
- Couldn't setState from the then function of the Promise
- What is the best way to have a React-generated static (SEO) "public" frontend alongside a CRA "private" app?
- Typescript in storybook with props type using parameter
- Why is JSON being detected as empty?
- "Cannot read properties of null (reading 'appendChild')" error in gatsby shows only on site refresh
- How to call a component function on other component, but from the other component ? React
- React-Redux and Utility class
- React + Redux: Separating the presentation from the data