将 Faker 与 Cypress 结合使用

Cla*_*ues 4 javascript faker cypress

我从 Cypress 开始,我想添加 Faker 来生成随机值。但我得到了以下结果。您能帮我解决这个问题吗?

登录页面.js

const faker = require('faker');

before(() => {
    let userData = {
        randomName: cy.faker.name.findName(),
        randomEmail: cy.faker.internet.email(),
        randomPassword: cy.faker.random.number()
    }
}

describe('Create new user', function () {
    it('Create new user via API', function () {
        cy.request('POST', '/cadastrarUsuario', {
            nome: userData.randomName,
            email: userData.randomEmail,
            senha: userData.randomPassword
        })
            .then((resp) => {
                expect(resp.status).to.eq(200)
            })
    })
})

describe('Login with user just created', function () {
    it('Login with user just created via API', function () {
        cy.request('POST', '/logar', {
            email: userData.randomEmail,
            senha: userData.randomPassword
        })
            .then((resp) => {
                expect(resp.status).to.eq(200)
            })
    })
})
Run Code Online (Sandbox Code Playgroud)

索引.js

cy.faker = require('faker');
Run Code Online (Sandbox Code Playgroud)

执行结果

TypeError: Cannot read property 'name' of undefined

Because this error occurred during a 'before all' hook we are skipping all of the remaining tests.
Run Code Online (Sandbox Code Playgroud)

Ric*_*sen 5

Cypress 与纯 JavaScript 配合得很好,因此让登录页面正常工作的最简单方法如下:

const faker = require('faker');

let userData = {
    randomName: faker.name.findName(),
    randomEmail: faker.internet.email(),
    randomPassword: faker.random.number()
}

describe('Create new user', function () {
    it('Create new user via API', function () {
        cy.request('POST', '/cadastrarUsuario', {
            nome: userData.randomName,
            email: userData.randomEmail,
            senha: userData.randomPassword
        })
            .then((resp) => {
                expect(resp.status).to.eq(201)
            })
    })
})
Run Code Online (Sandbox Code Playgroud)