You have missed out the code for MainPage, but I'm going to assume the open() method performs a cy.visit() which changes the win returned from cy.window(), so you are stubbing too early.
See Window Before Load shows how to stub correctly using the window:before:load event.
You also do not need the noisy assignment to win, at least for static methods.
MainPage
import MyCustomClass from './my-class'
class MainPage {
public open(): void {
cy.visit('https://example.com')
.then(() => {
// make sure you console.log after the window:before:load event
// i.e after the stub is set up
console.log('From MainPage (myMethod): ', MyCustomClass.myMethod())
})
}
}
export default MainPage;
Test
let mainPage: MainPage;
describe('stubs the static method', () => {
beforeEach(() => {
Cypress.on('window:before:load', () => {
console.log('From "window:before:load" event')
cy.stub(MyCustomClass, 'myMethod').returns('stubbed static value')
})
mainPage = new MainPage()
mainPage.open()
})
it('Test something', () => {
console.log('From the test: ', MyCustomClass.myMethod())
expect(MyCustomClass.myMethod()).to.eq('stubbed static value')
})
})
Cypress runner
Console