8

I am trying to use fakerjs in my cypress tests to randomly generate fake data for my forms. I have tried exporting it in support/index.js which did not work.

Is there any standard way to add fakerjs to all cypress specs instead of adding it in every spec file?

Anton Menshov
  • 2,266
  • 14
  • 34
  • 55
user1614862
  • 3,701
  • 7
  • 29
  • 46

3 Answers3

13

First off, what's wrong with importing it in every spec?

That being said, you can do this:

cypress/support/index.js:

cy.faker = require('faker');

your specs:

it(`test`, () => {
    const words = cy.faker.lorem.words();
});
dwelle
  • 6,894
  • 2
  • 46
  • 70
  • 2
    that's not working, when we call we calll cy.faker it is losing reference to existing selector, can we make it as utility, like we have lodash(Cypress._), moment.(Cypress.moment).etc – user1614862 Oct 14 '19 at 23:55
  • Not sure what "it is losing reference to existing selector" means. – dwelle Oct 15 '19 at 09:01
  • when I try to use faker like cy.get('#myinput').type(cy.faker.firstName()), it gives me an error that cy is not referring valid input to type – user1614862 Oct 15 '19 at 11:28
  • that has nothing to do with `cy.faker` but rather with `cy.type`. Solve the `cy.type` error (likely because the `cy.get()` didn't find an actionable element), and it'll work. – dwelle Oct 15 '19 at 12:30
  • 1
    cy.type() is working if I have simple text cy.get('#myinput').type('abc'), but it is failing with above error if I use cy.faker.firstName(), anyway, I am able to achieve this without cy. prefix, something like const faker = require('faker') and in my actual statement cy.get('#myinput').type(faker.firstName()). THANKS for the clue. – user1614862 Oct 15 '19 at 19:59
  • 2
    That doesn't make sense to me. Btw, `faker.firstName()` shouldn't work - the API is `faker.name.firstName()` (but maybe you're not on latest version). – dwelle Oct 15 '19 at 21:02
0

I tried it and found very simple. Steps are mentioned below,

1- require faker

const faker = require("faker");

2- Use where you want like this

var firstName = faker.Name.findName(); // Variable declaration
cy.get("#firstName").type(firstName); // Use in locator

I hope it would help :)

Valentine Shi
  • 6,604
  • 4
  • 46
  • 46
-1

For reference javascript :- Https://zetcode.com/javascript/fakerjs/

You can use these in cypress:

npm i faker

const faker = require("faker"); 

let username = faker.name.findName()
let email = faker.internet.email()
let password = faker.internet.password()

Use all these in single specs file.

Jason L.
  • 1,125
  • 11
  • 19
Tejas
  • 7
  • 1
  • 1
    Take a look at the following link to write a good answer: https://stackoverflow.com/help/how-to-answer – mohabbati Apr 09 '21 at 11:12