在Cypress中使用机会插件

时间:2019-07-08 07:18:12

标签: javascript cypress

是否可以将cypress插件与cypress.io一起使用?

https://chancejs.com

我通过npm将插件安装到node_modules \ chance并编辑了/plugins/index.js文件,但仍然从赛普拉斯那里收到错误-无法启动,插件文件丢失或无效。

如果不可能使用此插件-基于注册新用户,您建议编写什么测试?我计划利用机会生成“随机:电子邮件和密码。

// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************

// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)

module.exports = on => {
  on("task", {
    chance: require("chance"),
  });
};
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config
}

2 个答案:

答案 0 :(得分:3)

只需使用 npm 安装 chancejs:

npm install chance

然后在您的测试中使用它,例如:

/// <reference types="cypress" />

import Chance from 'Chance';

const chance = new Chance();

describe('Testing chance', function (){
   const company =chance.company();
   it('type company in duckduckgo.com', function () {
        cy.visit('https://duckduckgo.com/')
        cy.get('#search_form_input_homepage')
        .should('be.visible')
        .type(company)
    })
})

答案 1 :(得分:0)

cypress/support/index.js

覆盖默认的task命令,以便您可以像往常一样提供多个参数。

Cypress.Commands.overwrite('task', (origFn, name, ...args) => {
    return origFn(name, args);
});

// if you're gonna use `chance` plugin a lot, you can also add a custom command
Cypress.Commands.add('chance', (...args) => {
    return cy.task('chance', ...args);
});

cypress/plugins/index.js

将任务包装在函数中,该函数将散布参数,并处理任务不返回任何内容而返回null的情况,以使cypress不会抱怨。

const chance = require('chance').Chance();
// lodash should be installed alongside with cypress.
// If it doesn't resolve, you'll need to install it manually
const _ = require('lodash');

on('task', _.mapValues(
    {
        chance ( method, ...args ) {
            return chance[method](...args);
        }
    },
    func => args => Promise.resolve( func(...args) )
        // ensure we return null instead of undefined to satisfy cy.task
        .then( val => val === undefined ? null : val )
));

在您的规格文件中:

describe('test', () => {
    it('test', () => {
        cy.document().then( doc => {
            doc.body.innerHTML = `<input class="email">`;
        });

        cy.task('chance', 'email', {domain: 'example.com'}).then( email => {
            cy.get('.email').type(email);
        });

        // or use the custom `chance` command we added
        cy.chance('email', {domain: 'test.com'}).then( email => {
            cy.get('.email').type(email);
        });
    });
});
相关问题