Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress mock module federation micro frontent

My application has an auth micro frontend which creates a singleton instance for sharing the auth state with all the micro frontends in the application.

The auth class exposes some methods like so

{
    getUser: () => {...} 
    isAuthenticated: () => true
    ...
}

In the app I load in the MF, get the instance, and call the methods I need.

import { Auth } from 'auth/services/Auth';

const auth = Auth.getInstance();

const component = () => {
    const isAuthenticated = auth.isAuthenticated();
    ...
}

I use webpack module federation to load in the MF at run time.

    plugins: [
        new ModuleFederationPlugin({
            name: 'mf',
            remotes: {
                auth: 'auth@https://localhost:3099/remoteEntry.js',
                ...
            },
        }),
    ],

Is there a way I can mock the auth instance in Cypress? I would like to call the methods the auth instance exposes with mock data.

like image 965
Will Avatar asked Oct 14 '25 21:10

Will


1 Answers

One way of mocking the internals of an app is to expose a reference for the test to modify.

import { Auth } from 'auth/services/Auth';

const auth = Auth.getInstance();

if (window.Cypress) {
  window.auth
}

const component = () => {
    const isAuthenticated = auth.isAuthenticated();
    ...
}

test


cy.visit('/', {
  onBeforeLoad: (win) => {
    cy.stub(win.auth, 'isAuthenticated').returns(true)
  },
})
like image 127
TesterDick Avatar answered Oct 18 '25 00:10

TesterDick