My component is as follows
import {myMethod} from "./myFile"
function MyComponent(){
const output = myMethod();
console.log({output})
return <div></div>
}
And i am stubbing myMethod because I want it to return a specific value like so
import * as Parent from "./myFile"
cy.stub(Parent, "myMethod", () => "i was stubbed")
cy.visit("/my_component") # Does not use the stubbed function
but then i am finding that the component still uses the original function and not the stubbed function, does anyone know what i am doing wrong?
You have to setup babel plugin plugin-transform-modules-commonjs
with loose: true
[
'@babel/plugin-transform-modules-commonjs',
{
loose: true,
},
]
Example config of your cypress/plugins/index.js
const { startDevServer } = require('@cypress/webpack-dev-server');
const findReactScriptsWebpackConfig = require('@cypress/react/plugins/react-scripts/findReactScriptsWebpackConfig');
// taken from https://github.com/cypress-io/code-coverage/issues/461#issuecomment-859292331
function customDevServer(
on,
config,
{ webpackConfigPath } = {
webpackConfigPath: 'react-scripts/config/webpack.config',
}
) {
on('dev-server:start', async (options) => {
const webpackConfig = findReactScriptsWebpackConfig(config, {
webpackConfigPath,
});
const rules = webpackConfig.module.rules.find((rule) => !!rule.oneOf).oneOf;
const babelRule = rules.find((rule) => /babel-loader/.test(rule.loader));
babelRule.options.plugins.push(require.resolve('babel-plugin-istanbul'), [
'@babel/plugin-transform-modules-commonjs',
{
loose: true,
},
]);
return startDevServer({
options,
webpackConfig,
});
});
config.env.reactDevtools = true;
return config;
}
module.exports = (on, config) => {
if (config.testingType === 'component') {
customDevServer(on, config);
}
require('@cypress/code-coverage/task')(on, config);
return config;
};
The issue link on github: https://github.com/cypress-io/cypress/issues/18662