I'm attempting to stub a React hook. A simplified view of the code under test would be:
// component.tsx
import { useNavigate } from 'react-router-dom';
export default function Component() {
const navigate = useNavigate();
// ...
}
The test attempts to stub useNavigate like this:
// component.cy.tsx
import * as reactRouterDom from 'react-router-dom';
cy.stub(reactRouterDom, 'useNavigate')
.as('useNavigateStub')
.callsFake(() => {
console.log(` fake useNavigate`); // <-- this never happens
});
console.log(` stub: ${reactRouterDom.useNavigate}`); // This prints out the original `useNavigate` function, not a stub
cy.mount(<Component/>);
I've tried following the advice here: https://github.com/cypress-io/cypress/tree/master/npm/react/cypress/component/advanced/mocking-imports here: https://github.com/sinonjs/sinon/issues/1711 and here: https://github.com/cypress-io/cypress/issues/17048
But I can't get it to work, presumably because of something to do with the webpack configuration I already have. I've done a lot of attempted tweaking there to make this work so I'm not sure I can even remember it all, but for example I've tried replacing the ts-loader rule with a babel-loader rule with the config suggested in the link above and it just hangs forever. Using ts-loader I can't find any configuration that allows stubbing to work at all.
My current cypress configuration looks like this:
{
component: {
devServer: {
framework: 'react',
bundler: 'webpack',
webpackConfig: {
entry: './src/index.ts',
output: {
path: '<repo>/dist/1.35.6',
publicPath: 'auto'
},
mode: 'development',
resolve: {
extensions: [ '.ts', '.tsx', '.js', '.jsx' ],
alias: {
'~': '<repo>/src',
test: '<repo>/test'
}
},
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
loader: 'ts-loader',
exclude: /node_modules/
},
{ test: /\.svg/, type: 'asset/inline' },
{ test: /\.png/i, loader: 'file-loader' }
]
},
plugins: [
Dotenv {
config: {
path: './.env',
prefix: 'process.env.',
systemvars: true
}
},
ModuleFederationPlugin {
// very long config object that seems unimportant
},
HtmlWebpackPlugin {
userOptions: { template: './public/index.html' },
version: 5
}
],
devtool: 'cheap-module-source-map',
devServer: { port: '3003', open: false, historyApiFallback: true }
}
}
}
}
Mostly I've been trying to tweak this bit to try different loaders and options:
{
test: /\.(js|jsx|ts|tsx)$/,
loader: 'ts-loader',
exclude: /node_modules/
},
Is there something I'm doing fundamentally wrong? The error messages (when I get them) are very unhelpful and most of the time there's no feedback at all so I'm not really sure how to debug this. Any assistance to get me going in the right direction would be helpful.