Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not able to fire API call in Jest for react component imported in another react component #38

Open
Shwetharao opened this issue Apr 3, 2022 · 0 comments

Comments

@Shwetharao
Copy link

I am trying to test Button click function in jest. These are my code.

mainComponent.js

 export default function MainComponent(){
     const saveApiSettings = () => {
     apiCall('rest/test_api/').then(res => {
      console.log(res)
    });
   }
 return( 
  <div>
   <CommonModule
    saveApiData={ saveApiSettings}
   />
 </div>)
}

commonModule.js

   export default function CommonModule() {
        const saveData = () => {
         props.saveApiData();
        }
        return (
         <Button
          onClick = {(e) => saveData(e)}
          id = "save-btn"
         >
          click
         </Button>
        )
      }

test.js

 it('save data to DB', async () => {
   act(() => {
    render(<MainComponent />);
   });
   act(() => {
    const checkSaveBtnenable = document.querySelector(`button[id = 'save-btn']`);
    checkSaveBtnenable.dispatchEvent(new MouseEvent("click", { bubbles: true }));
  });

handler.js

import { rest } from 'msw';
 export const handlers = [
  rest.post(`rest/test_api/`, async (req, res, ctx) => {
   console.log(req, "Not printing");
  })
 ]

It seems like its not able to hit API from test file. I am using MSW (Mock Server Work) to mock API calls. Its look like I am loading main component and trying to access another component click. I am not able to hit API defined in handler.js.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant