0

I am trying to write "unit-test" for components in react with cypress.
Followed the link cypress docs on component testing

when I wrote testcase for a component and tried to run with "npx cypress open-ct"
then getting the above error (question title)...
Note: for login oAuth2 is implemented !!!
My index.spec.js file is

import * as React from 'react';
import { mount } from '@cypress/react';
import User from './index';

describe('User component', ()=>{
    before('loginApi', ()=>{
        cy.login();  
        //login() has login-logic and setting localStorage (placed in "commands.js" file)  
        //even if cy.login() is commented, error is same (so guessing this not reason of error)
    })
    it('Mount user', () => {            
        mount(<User />); 
    });
})

Observation1: on cypress browser under TEST BODY "mount" value is <Unknown.../>
Observation2: [Network tab] User component makes api-call and failing with 401
(#known token issue, even fails with right token)

Find attached error screenshot. error screenshot

CodeWorld
  • 2,017
  • 1
  • 11
  • 21

2 Answers2

1

After some beating around I found out...

  1. mount <Unknown... /> basically thrown in the case, if you have not added all the dependencies which are used in respective index.jsx file.

  2. useNavigation() may be used only in context is thrown in the case, if you are missing BrowserRouter dependency the way you have used in your routing page (either one)
    import {BrowserRouter as Router} from 'react-router-dom';
    import {BrowserRouter} from 'react-router-dom';

    import * as React from 'react';  
    import { mount } from '@cypress/react';  
    import User from './index';  
    import {BrowserRouter as Router} from 'react-router-dom';   
    
    describe('User component', ()=>{
       it('Mount user', () => {   
          const onSubmit= cy.stub();  
          //or any other function which is probably used by ur component         
          mount(
            <Router>      
               <User onSumbit={onSubmit}/>
            </Router>
          ); 
       });
    });
    
CodeWorld
  • 2,017
  • 1
  • 11
  • 21
0

Adding to what CodeWorld said, this error occurs because your component depends on react-router-dom so you have to tell Cypress to mount your component whilst been wrapped inside BrowserRouter.

Personally, I like to create a custom command to abstract the mounting process (useful for providers that are nested):

// cypress/support/commands.js
Cypress.Commands.add('mountWithProviders', (children: ReactNode) => {
  cy.mount(
    <BrowserRouter>
      <AnotherProvider>
        <AnotherProvider2>{children}</AnotherProvider2>
      </AnotherProvider>
    </BrowserRouter>
  );
});

// index.spec.js
cy.mountWithProviders(<Signin />);
JoshX
  • 49
  • 4