How to properly add a class inside Cypress code - javascript

I am learning Cypress along with JavaScript. I am running into a problem that I am not certain how to search it into documentation. The site I started testing has the typical wait issues so I encountered a very good solution here.
Now my test is looking in this way
/// <reference types="Cypress" />
let appHasStarted
function spyOnAddEventListener (win) {
// win = window object in our application
const addListener = win.EventTarget.prototype.addEventListener
win.EventTarget.prototype.addEventListener = function (name) {
if (name === 'change') {
// web app added an event listener to the input box -
// that means the web application has started
appHasStarted = true
// restore the original event listener
win.EventTarget.prototype.addEventListener = addListener
}
return addListener.apply(this, arguments)
}
}
function waitForAppStart() {
// keeps rechecking "appHasStarted" variable
return new Cypress.Promise((resolve, reject) => {
const isReady = () => {
if (appHasStarted) {
return resolve()
}
setTimeout(isReady, 0)
}
isReady()
})
}
describe('Main test suite', () => {
beforeEach(() => {
cy.visit('http://mercadolibre.com.ar',{
onBeforeLoad: spyOnAddEventListener
}).then({ timeout: 10000 }, waitForAppStart)
})
it('search first scanner', () => {
cy.contains('nav-search-input').type("scanner bluetooth para auto")
})
})
The problem with this is, I should replicate spyOnAddEventListener, waitForAppStart and variable appHasStarted at the beginning of every source file but I want to avoid this. How could properly extend this functions as a part of the internal source project without replicating in every test source? I have tried to make a simple source JavaScript file at the root of the project but when I import it, Cypress clients give an unrelated plug error like this one:

It looks like you've added the code to /cypress/plugins/index.js, but that is for task extensions (code that requires NodeJS access).
The two functions can be added to a file, ideally in the /cypress/support folder
wait-for-app-utils.js
let appHasStarted
function spyOnAddEventListener (win) {
...
}
function waitForAppStart() {
...
}
module.exports = {
spyOnAddEventListener,
waitForAppStart
}
test
import {spyOnAddEventListener, waitForAppStart} from '../support/wait-for-app-utils.js'
describe('Main test suite', () => {
beforeEach(() => {
cy.visit('http://mercadolibre.com.ar', {
onBeforeLoad: spyOnAddEventListener
}).then({ timeout: 10000 }, waitForAppStart)
})
Another approach is to wrap it all up (including the visit) into a custom command. Now there's no need to export and import, the command will be available globally.
/cypress/support/commands.js
let appHasStarted
function spyOnAddEventListener (win) {
...
}
function waitForAppStart() {
...
}
Cypress.Commands.add('visitAndWait', (url) =>
cy.visit(url, { onBeforeLoad: spyOnAddEventListener })
.then({ timeout: 10000 }, waitForAppStart)
)
test
describe('Main test suite', () => {
beforeEach(() => {
cy.visitAndWait('http://mercadolibre.com.ar')
})

Related

Cypress not intercepting request with render function vue

I'm trying to do a pretty simple intercept in Cypress using a Vue's application. My component has a setup method using render function as such:
setup() {
useInfiniteLoading({ runner: ... })
}
Then on my tests I do the following:
describe("List todo resource", () => {
it("Checks it loads more todos when scrolling to the bottom", function () {
cy.intercept('/todo').as('getTodos');
cy.visit("/todos");
cy.wait("#getTodos").then(({response}) => {
console.log(response);
})
})
})
When running the test I see that the intercept is not stubbing the response.
As you can see from the image the request makes a request to my actual server running locally and the response is stubed. The weird part is that in a previous test I have:
it("Checks the todo list gets updated when clicking on to resolve it (from true to false)", function () {
cy.visit("/todos");
const resolved = false;
const shouldHaveClass = resolved
? "mdi-checkbox-marked-outline"
: "mdi-checkbox-blank-outline";
cy.intercept("GET", "todo", {
fixture: "resources/todo/list.todo.json",
}).as("getTodos");
cy.intercept("PUT", "todo", {
body: { data: { ...this.updateTodoFixture.data, resolved } },
}).as("updateTodo");
cy.get(".todo-list-item__resolve")
.first()
.each((btn) => {
btn.click();
});
cy.get(".todo-list-item__resolve")
.first()
.should("satisfy", ($el) => {
const classList = Array.from($el[0].classList);
return classList.includes(shouldHaveClass);
});
});
And the response is stubbed using intercept as you can see from the previous screenshot. Is it possible that the previous test is affecting the next test? I have tried taking a look into "Intercept too soon" but no luck on trying to apply the fix described in the page.
Any idea on what could be causing the stub not to happen?

Cypress: Page doesn't load within the second 'it' block for the click action

It works fine for the same click event if I've coded within the single 'it' block as below.
Working code:
describe('Test Suite', () => {
it('Test case 1', () => {
//Test 1
//Test 2
})
})
Not working:
describe('Test Suite', () => {
it('Test case 1', () => {
//Test 1
})
it('Test case 2', () => {
//Test 2
})
})
Below is my code snippet, First 'it' block works fine after login method executes. Then second it blocks just clicking the right element but the page never loads.
P.S. If I written the code under the single 'it' block, Page loads and works fine.
describe('Fund Manager Suite', () => {
//Checking Fund Manager page loading
before(() => {
cy.visit('xxxxxxxxxxxxx')
cy.login('xxxxx', 'xxxxx')
})
it('fund manager navigation works', () => {
cy.location('pathname').should('equal', '/xxxxx')
cy.get('#appSwitcher').click()
cy.get('#appSwitcher > .dropdown > .dropdown-menu > :nth-child(2) > a').click()
cy.location('pathname').should('equal', '/xxxxx')
cy.get('.k-grid-table').find('tr').should('have.length', 5)
})
it('fund detail works', () => {
cy.get('.product > :nth-child(2)').click()
cy.location('pathname').should('equal', '/xxxxx')
// Fund Detail - Search
cy.get('#s2id_autogen31').type('Rach')
cy.get('#select2-result-label-32').click()
cy.get('#searchSubmit').click()
cy.get('#DataTables_Table_0').find('tr').should('have.length', 10)
})
})
Execution Screen shot
Code snippet screen shot
You have to preserve your cookies in beforeEach() to make sure that you stay logged in, in all it() blocks. You can read more in cypress docs.
describe('Dashboard', () => {
before(() => {
// log in only once before any of the tests run.
// your app will likely set some sort of session cookie.
// you'll need to know the name of the cookie(s), which you can find
// in your Resources -> Cookies panel in the Chrome Dev Tools.
cy.login()
})
beforeEach(() => {
// before each test, we can automatically preserve the
// 'session_id' and 'remember_token' cookies. this means they
// will not be cleared before the NEXT test starts.
//
// the name of your cookies will likely be different
// this is an example
Cypress.Cookies.preserveOnce('session_id', 'remember_token')
})
it('displays stats', () => {
// ...
})
it('can do something', () => {
// ...
})
it('opens a modal', () => {
// ...
})
})
I Have seen this kind of behavior, when the first it case start and doesn`t finish some xhr request in the site - and in result cypress continues the process during the start of the second it case. The best solution for clean slate for each case I had found is to separate every case in different file
Update:
Able to resolve this issue by storing the session_id.
Cypress.Cookies.defaults({
preserve: "session_id"
})

How to fix the Error "TypeError: cy.[custom command] is not a function"?

I have written some function in commands.js file for cypress automation testing, out of which I am able to invoke only one i.e."login" but unable to invoke other functions form another .js file. Cypress Test Runner showing
"TypeError: cy.FillAddCaseDetails is not a function"
describe('Adding a Case on CSS Poratal ', function() {
before(function () {
cy.login() // calling login function successfully
})
it('open add case',function(){
cy.wait(9000)
cy.hash().should('contains','#/home')
cy.wait(['#GETcontentLoad']);
cy.wait(['#POSTcontentLoad']);
cy.get('[uib-tooltip="Add Case"]').click({force:true})
cy.log('clicked on Add case')
cy.wait(3000)
cy.get('[ng-click="lookup.cancel()"]').click({force: true})
cy.get('[ng-click="lookup.closeAddCase()"]').click({force: true})
cy.get('[uib-tooltip="Add Case"]').click({force:true})
cy.wait(3000)
cy.get('[ng-model="lookup.selectedPartner"]',{force:true})
.type(AddJob.JobData.Partner,{force: true})
cy.xpath('//input[#ng-model="lookup.selectedPartner"]')
.should('be.visible').then(() => {
cy.FillAddCaseDetails() // unable to call
cy.FillCustomerDetails() // unable to call
})
Function:
Cypress.Commands.add("FillCustomerDetails", () => {
cy.get('[ng-model="lookup.firstName"]')
.type(AddJob.JobData.FirstName, { force: true})
cy.get('[ng-model="lookup.lastName"]')
.type(AddJob.JobData.LastName, { force: true })
cy.get('[ng-model="lookup.customerPhone"]')
.type(AddJob.JobData.CustomerPhone, { force: true })
cy.get('[value="NEXT"]').click({ force: true })
})
expected : function will get called
actual : TypeError: cy.FillAddCaseDetails is not a function
This is the top result for this error so I would like to add what I did to fix it. This is relevant to version >=10 and typescript. The problem ended up being that the supportFile setting in cypress.config.ts was set to false; I changed my config to this:
import cypress, { defineConfig } from 'cypress'
export default defineConfig({
e2e: {
'baseUrl': 'http://localhost:4200',
supportFile: 'cypress/support/e2e.ts'
},
})
I created the custom commands in commands.ts
declare namespace Cypress {
interface Chainable<Subject = any> {
/**
* Custom command to select DOM element by data-cy attribute.
* #example cy.dataCy('greeting')
*/
clearIndexedDB(): Promise<void>
}
}
Cypress.Commands.add('clearIndexedDB', async () => {
const databases = await window.indexedDB.databases();
await Promise.all(
databases.map(
({ name }) => {
if (!name) return
return new Promise((resolve, reject) => {
const request = window.indexedDB.deleteDatabase(name);
request.addEventListener('success', resolve);
request.addEventListener('blocked', resolve);
request.addEventListener('error', reject);
})
},
),
);
});
Then I uncommented this line in my e2e.ts file
import './commands';
In my case solution was a restart of the cypress test runner.
If you added your Custom Command to support/commands.js file, You need to import that file from support/index.js file. Create support/index.js, if it's not available and add the line import "./commands.js" to it.
From the Cypress docs: https://on.cypress.io/typescript#Types-for-custom-commands
if you add the command cy.dataCy into your supportFile like this:
// cypress/support/index.js
Cypress.Commands.add('dataCy', (value) => {
return cy.get(`[data-cy=${value}]`)
})
Then you can add the dataCy command to the global Cypress Chainable interface (so called because commands are chained together) by creating a new TypeScript definitions file beside your supportFile, in this case at cypress/support/index.d.ts.
// in cypress/support/index.d.ts
// load type definitions that come with Cypress module
/// <reference types="cypress" />
declare namespace Cypress {
interface Chainable {
/**
* Custom command to select DOM element by data-cy attribute.
* #example cy.dataCy('greeting')
*/
dataCy(value: string): Chainable<Element>
}
}
cy.xpath("//div[#class='c-navigatorItem-faceplate ng-scope ng-isolate-scope']").click();
Is it a valid to use because I am getting the TypeError cy.xpath is not a function

Apollo MockedProvider testing issues (my rendered component keeps disappearing)

Disclaimer; I'm a bit new to react-testing-library (been using an admittedly older version of Enzyme) and the Apollo Query/MockedProvider components (been using the client via a JS service object), so this may be a stupid question...
I have a component that receives a list of countries for which I am trying to write tests. What I would like to do is something like:
import React from 'react';
import { MockedProvider } from '#apollo/react-testing';
import { render, act } from '#testing-library/react';
import wait from 'waait';
import Countries, { countryQuery } from './Countries';
import { isTerminating } from 'apollo-link/lib/linkUtils';
const mockCountryName = 'sample country';
const mocks = [
{
request: {
query: countryQuery,
vairables: {},
},
result: {
data: {
countries: [{ name: mockCountryName }],
},
},
},
];
describe('when working with the countries component', () => {
describe('and the component is loading', () => {
let component;
beforeAll(async (done) => {
await act(async () => {
component = render(
<MockedProvider mocks={[]}>
<Countries />
</MockedProvider>
);
});
done();
});
it('should have a title', () => {
expect(component.getByText('Countries Component')).not.toBeUndefined();
});
it('should have a loading status', () => {
expect(component.getByText('Loading...')).not.toBeUndefined();
});
});
});
When this runs, the second test (about loading status) fails as it looks like the component is only a body tag at that point. I tried changing beforeAll to beforeEach, but that just produced a component that had an Error indicator. I put some console.log statements in my component, and this is what they are showing me:
console.log src/components/Countries.js:45
Loading is: true
console.log src/components/Countries.js:46
Error is: undefined
console.log src/components/Countries.js:45
Loading is: false
console.log src/components/Countries.js:46
Error is: Error: Network error: No more mocked responses for the query: {
countries {
name
phone
__typename
}
}
, variables: {}
I'm wondering if it does not like the empty array passed in as the mocks property for the MockedProvider. But every example I've seen does it that way, so...
As an experiment, I added a second set of test to the spec file to see if it was just a weird timing issue with the component that was causing the issue. Here's the second test:
describe('and the component has data', () => {
let component;
beforeAll(async (done) => {
await act(async () => {
component = render(
<MockedProvider mocks={mocks} addTypename={false}>
<Countries />
</MockedProvider>
);
await wait(0);
});
done();
});
it('should have a title', () => {
expect(component.getByText('Countries Component')).not.toBeUndefined();
});
it('should have a loading status', () => {
expect(component.getByText(mockCountryName)).not.toBeUndefined();
});
});
This has the same problem; the first test works (if I reorder the test, the one that first always works) but the second one fails, and the component seems to be an empty body tag.
Is there a way to make this type of test structure work? I don't like the idea of having to put everything into a single test, let alone the setup code for the component.
Thanks!
I'm not sure if it's the best approach, but I think I found a workaround.
First, the empty array/loading issue was not an issue; I traced everything back to testing-library resetting/re-rendering the component between tests.
Here's what I did:
describe('and the component is loading', () => {
let component, pageTitle, loadingMessage;
beforeAll(async (done) => {
await act(async () => {
component = render(
<MockedProvider mocks={[]}>
<Countries />
</MockedProvider>
);
pageTitle = component.getByText(mockPageTitle);
loadingMessage = component.getByText(mockLoadingMessage);
});
done();
});
it('should have a title', () => {
expect(pageTitle).not.toBeUndefined();
});
it('should have a loading status', () => {
expect(loadingMessage).not.toBeUndefined();
});
});
Instead of trying to call component.getTextBy in each test, I moved them into the beforeAll, and assigned the output to variables. Each test uses the variables for their tests. I also wrote a test for my Routes component, and I was still able to call fireEvent.click() on the components.
I would be very interested in any feedback from anyone who has a more experience with testing-library on this. It seems better than what I had, but I want to make sure it's really the best approach.
Thanks.

Jest: Testing API Methods from Intercom

I am having trouble understanding what the testing flow would be for testing functions which use functions loaded from a JavaScript library from Intercom.
My method looks like this:
export const generateButton = (handleOnClick) => {
case "moo":
return <button onClick={() => Intercom('show')}>Sign Up</button>
default:
return 'moo'
The error I get when running this is:
ReferenceError: Intercom is not defined
So I figured it out, I needed to add a new file and point jest set up on package.json to it like so (the file added is mockObject)
"setupFiles": [
"./config/jest/setupJest.js",
"./config/jest/mockObject.js"
],
then in the file itself has this in it
global.Intercom = () => {
console.log('Intercom called')
}
If I understand what you're trying to do then create a dummyFunction to replace Intercom in your tests. Something like this...
const Intercom = jest.fn();
describe('button click', () => {
it('Intercom is called correctly', () => {
// whatever component contains the button should be mounted
const wrapper = mount(<YourComponentHere />);
// you may need to add a class to target the specific button
wrapper.find('button').simulate('click');
expect(dummyFunction).toHaveBeenCalledWith('show');
expect(dummyFunction).toHaveBeenCalledTimes(1);
});
});

Categories

Resources