I'm looking for a way to expect a canceled request with cypress. Any idea? :)
I cancel the previous requests if the user sends too many requests and I want to test it.
I tried to intercept POST requests with the alias, counted requests,...
Commands are running on a queue which works asynchronously from the javascript.
To assert the counter value after the queue has run, wrap the assertion in a .then().
let counter;
When('I click on the refresh button', () => {
cy.wait(2000);
cy.window().then(window => window.msw.worker.stop());
cy.intercept('POST', 'myApi', {
body: {
items: []
}
}).as('search');
client.SearchBar.refresh();
cy.wait('#search').then(interceptor > {
counter++;
console.log('Interceptor', interceptor.request,
'Response', interceptor?.response,
'\nCounter', counter)
});
cy.then(() => {
expect(counter).to.be.not.eq(2);
})
...
})
Related
According to the Cypress Cucumber Preprocessor docs regarding Before and After hooks:
The cypress-cucumber-preprocessor supports both Mocha's before/beforeEach/after/afterEach hooks and Cucumber's Before and After hooks.
However for some reason it doesn't seem to support the Cucumber's BeforeAll and AfterAll hooks. This is somewhat problematic for me. I'm currently trying to write some API tests that need to use an auth token that can only be obtained by manually logging in to the site first.
Ideally I would like my tests to log in through the UI only once, grab the auth token, and then run all of my API tests using that auth token.
I have all of these API scenarios tagged with #api and would love to be able to use a BeforeAll({ tags: '#api' }, () => { function (or equivalent) to have my Cypress tests log in and grab the auth token for use in those scenarios. However it seems like my only options are:
Use Before instead of BeforeAll (which would force me to login through the UI for every single scenario with the #api tag even though should I only need to do it once)
Use a Background on the feature file (which has the same problem)
Use Mocha's before hook instead of Cucumber's (which unfortunately doesn't support tagging and therefore would run before every feature file, instead of just the ones I have tagged)
Is there no way to replicate the Cucumber BeforeAll functionality with Cypress-Cucumber-Preprocessor?
The way I would approach the problem is to flag the first login in the run, and prevent the login code from running once the flag is set.
let loggedIn = false;
Before(() => {
const tags = window.testState.pickle.tags.map(tag => tag.name)
if (tags.includes('#api') && !loggedIn) {
loggedIn = true
console.log('logging in') // check this is called once
// do the login
}
})
You should also be able to get the same effect by wrapping the login code in a cy.session(), which is a cache that only runs it's callback once per run.
Before(() => {
const tags = window.testState.pickle.tags.map(tag => tag.name)
if (tags.includes('#api')) {
cy.session('login', () => {
console.log('logging in') // check this is called once
// do the login
})
}
})
Update from #rmoreltandem
This syntax is simpler
let loggedIn = false;
Before({ tags: '#api' }, () => {
if (!loggedIn) {
loggedIn = true
console.log('logging in') // check this is called once
// do the login
}
})
with session
Before({ tags: '#api' }, () => {
cy.session('login', () => {
console.log('logging in') // check this is called once
// do the login
})
})
I'm testing MyComponent that, in ngOnInit, calls a service method that returns an observable:
this.myService.getMyData().subscribe(
(data) => {
//do something
},
(error) => {
//do something - error
}
);
I've installed a spy on getMyData, this way:
mySpy = spyOn(myService, 'getMyData').and.returnValue(of(mockObject));
and this covers the "success branch" of subscribe. But I need also to cover the "error branch". I've tried doing this:
spyOn(myService, 'getMyData').and.returnValue(throwError(new Error('Error')));
but of course Jasmine tells me that getMyData has already been spied upon. How can I cover both branches?
What you are doing is correct but, you can't spy on the same service more than once in the same test case.
Hence you need to write a second test case which will cover your error scenario.
Something like this:
it('should run success scenario', () => {
mySpy = spyOn(myService, 'getMyData').and.returnValue(of(mockObject));
})
it('should run error scenario', () => {
mySpy = spyOn(myService, 'getMyData').and.returnValue(throwError(new Error('Error')));
})
I'm visiting a page which is fetching data Asynchronously (multiple XHR requests), and then asserting if a certain DOM element is visible/exists in the page.
So far I was only able to get the page and the data fetched with using cy.wait() either with an arbitrary time, or by aliasing the actual request, and using the promise-like syntax to make sure my cy.get() is done after the XHR response has completed.
Here is what doesn't work:
before(() => {
cy.login();
cy.server();
cy.route('/v0/real-properties/*').as('getRealPropertyDetails');
cy.visit('/real-properties/1/real-property-units-table');
});
beforeEach(() => {
Cypress.Cookies.preserveOnce('platform_session');
});
after(() => {
cy.clearCookies();
});
context('when viewport is below 1367', () => {
it('should be closed by default', () => {
cy.wait('#getRealPropertyDetails'); // the documentation says this is the way to go
sSizes.forEach((size) => {
cy.viewport(size[0], size[1]);
cy.get('.v-navigation-drawer--open.real-property-details-sidebar').should('not.exist');
});
});
Adding cy.wait(1000); in the before() or beforeEach() hooks also works, but this is not really an acceptable solution.
What works, but not sure if this is the way to do this (I would have to add this for every page, would be quite annoying) :
it('should be closed by default', () => {
cy.wait('#getRealPropertyDetails').then(() => {
sSizes.forEach((size) => {
cy.viewport(size[0], size[1]);
cy.get('.real-property-details-sidebar').should('not.be.visible');
});
});
});
I see that you have browser reloads there (beforeEach), which could potentially wipe out the route spy, but not sure why cy.wait().then would work. I would try switching from before to beforeEach though, creating things once is always trickier than letting them be created before each test
Although I know this may not be considered as a best practice, but what I want to achieve is to silently delete a record from a database after the same was created throughout UI. In htat way I want to keep our test environment clear as much as possible and reduce the noise of test data.
After my tests create a new record by clicking over the UI, I wait for POST request to finish and then I would like to extract the id from the response (so I can reuse it to silently delete that record by calling the cy.request('DELETE', '/id')).
Here's a sample test I have put on as a showcase. I'm wondering why nothing is logged in this example.
it('GET cypress and log', () => {
cy.server()
.route('**/repos/cypress-io/cypress*')
.as('getSiteInfo');
cy.visit('https://www.cypress.io/dashboard');
cy.get('img[alt="Cypress.io"]')
.click()
.wait('#getSiteInfo')
.then((response) => {
cy.log(response.body)
})
})
As far as I can see from here https://docs.cypress.io/api/commands/wait.html#Alias this should be fine.
your code contains two problems.
First:
The click triggers a new page to be loaded but cypress does not wait until the PageLoad event is raised (because you do not use visit). On my PC the Request takes about 5 seconds until it is triggered after the click. So you should use wait(..., { timeout: 10000 }).
Second:
wait() yields the XHR object, not the response. So your code within then is not correct. Also the body is passed as object. So you should use JSON.stringify() to see the result in the command log.
This code works:
describe("asda", () => {
it('GET cypress and log', () => {
cy.server()
.route('**/repos/cypress-io/cypress*')
.as('getSiteInfo');
cy.visit('https://www.cypress.io/dashboard');
cy
.get('img[alt="Cypress.io"]')
.click()
.wait('#getSiteInfo', { timeout: 20000 })
.then((xhr) => {
cy.log(JSON.stringify(xhr.response.body))
})
})
})
Instead of route and server method, try intercept directly
I have been attempting to create some cycle.js examples as nested dialogues, and switching between them using a select box.
One of the dialogues is a clone of the official Github HTTP Search example.
The other dialogue a more basic one which does not have HTTP, only DOM.
I feel like I wrapped my head around switching between the 2, but I'm fairly new to Rx so that may be done incorrectly or naively.
It all seemed to work well until I added a loading indicator to the search page.
To do that, I turned this:
const vTree$ = responses.HTTP
.filter(res$ => res$.request.indexOf(GITHUB_SEARCH_API) === 0)
.flatMapLatest(x => x)
.map(res => res.body.items)
.startWith([])
.map(results =>
h('div.wrapper', {}, [
h('label.label', {}, 'Search:'),
h('input.field', {type: 'text'}),
h('hr'),
h('section.search-results', {}, results.map(resultView)),
])
)
Into this:
const searchResponse$ = responses.HTTP
.filter(res$ => res$.request.indexOf(GITHUB_SEARCH_API) === 0)
.flatMapLatest(x => x)
.map(res => res.body.items)
.startWith([])
const loading$ = searchRequest$.map(true).merge(searchResponse$.map(false))
// Convert the stream of HTTP responses to virtual DOM elements.
const vtree$ = loading$.withLatestFrom(searchResponse$, (loading, results) =>
h('div.wrapper', {}, [
h('label.label', {}, 'Search:'),
h('input.field', {type: 'text'}),
h('span', {}, loading ? 'Loading...' : 'Done'),
h('hr'),
h('section.search-results', {}, results.map(resultView)),
])
)
I now have 2 issues
The 'checkbox value set to' and 'route changed' messages are logged
twice for every change of the checkbox.
The HTTP request log only
fires once, but if you watch the network activity in Dev Tools
you'll see two GET requests simultaneously.
Thanks for any help!
EDIT: Solved my own problem. See answer below.
I ended up solving this problem by rebuilding my entire application from scratch until I found the breaking point.
What I learned is that you need to add .share() to any observable stream which will be subscribed/mapped/etc by more than one downstream observable.
const searchRequest$ = DOM.select('.field').events('input')
.debounce(500)
.map(ev => ev.target.value.trim())
.filter(query => query.length > 0)
.map(q => GITHUB_SEARCH_API + encodeURI(q))
.share() //needed because multiple observables will subscribe
// Get search results from HTTP response.
const searchResponse$ = HTTP
.filter(res$ => res$ && res$.request.url.indexOf(GITHUB_SEARCH_API) === 0)
.flatMapLatest(x => x) //Needed because HTTP gives an Observable when you map it
.map(res => res.body.items)
.startWith([])
.share() //needed because multiple observables will subscribe
//loading indication. true if request is newer than response
const loading$ = searchRequest$.map(true).merge(searchResponse$.map(false))
.startWith(false)
.share()
//Combined state observable which triggers view updates
const state$ = Rx.Observable.combineLatest(searchResponse$, loading$,
(res, loading) => {
return {results: res, loading: loading}
})
//Generate HTML from the current state
const vtree$ = state$
.map(({results, loading}) =>
.........