phongnd39 / cypress-jest-adapter

Add jest assertion style to Cypress expect command
MIT License
93 stars 5 forks source link

Example of testing DOM? #8

Closed talentlessguy closed 5 years ago

talentlessguy commented 5 years ago

I am new to Cypress and I don't get how I should write tests with Jest adapter.

I have this:

describe('Index page', () => {
  beforeEach(() => {
    cy.log(`Visiting http://localhost:3000`)
    cy.visit('/')
  })

  it('should render logo icon', () => {
    cy.get('a[href="/"] > img').should('have.length', 1)
  })
})

But it isn't Jest. I want something like expect(cy.get('a[href="/"] > img').toJSON()).toHaveProperty('height', '7vh'). How can I do it? I checked the examples and I didn't see cy.get there.

phongnd39 commented 5 years ago

When testing DOM elements with this adapter, you can write something like this:

describe('Index page', () => {
  beforeEach(() => {
    cy.log(`Visiting http://localhost:3000`)
    cy.visit('/')
  })

  it('should render logo icon', () => {
    cy.get('a[href="/"] > img').should('have.length', 1)
    // equivalent check
    cy.get('a[href="/"] > img').then($el => {
      expect($el).toHaveLength(1) // this one is from jest
      expect($el.length).toEqual(1) // this one is from jest
      expect($el).toHaveQuantity(1) // this one is from jest-jquery
    })
    cy.get('a[href="/"] > img').should('toHaveQuantity', 1) // you can use jest matcher in should(), too
  })
})

Of course you can use jest matcher outside cy.get, too.

it('do something', () => {
  expect(true).toEqual(true)
})

You might want to write something like this

expect(cy.get('a[href="/"] > img').toJSON()).toHaveProperty('height', '7vh')

but this is not how Cypress work. You can read more about this here

If you still want to use the above syntax, i think you could take a look on this project: https://github.com/NicholasBoll/cypress-promise, as it makes Cypress command to return promise and you can use async/await there, and test the resolve value with this adapter directly. But it might have some caveats.

I will update the example and readme to add some examples later. Thanks

talentlessguy commented 5 years ago

@phongnd39 thank you for explanation. Would be cool to put this into examples because mostly Jest is used for testing React, and DOM too.