忽略Cypress.io上的存根函数

Stubbing functions on Cypress.io being ignored(忽略Cypress.io上的存根函数)

本文介绍了忽略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

这篇关于忽略Cypress.io上的存根函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:忽略Cypress.io上的存根函数