忽略Cypress.io上的存根函数
我的组件如下
import {myMethod} from "./myFile"
function MyComponent(){
const output = myMethod();
console.log({output})
return <div></div>
}
我正在存根myMethod,因为我希望它返回如下所示的特定值
import * as Parent from "./myFile"
cy.stub(Parent, "myMethod", () => "i was stubbed")
cy.visit("/my_component") # Does not use the stubbed function
但是我发现组件仍然使用原始函数而不是存根函数,有人知道我做错了什么吗?
解决方案
您必须使用loose: true
plugin-transform-modules-commonjs
[
'@babel/plugin-transform-modules-commonjs',
{
loose: true,
},
]
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;
};
GitHub上的问题链接:https://github.com/cypress-io/cypress/issues/18662
相关文章