I'm trying to loop over an array of strings in order to use the same logic for all tests but for different device sizes. However I can't figure out how to make TypeScript happy with the type for 'ViewportPreset'. Here is how the test file looks:
/// <reference types="Cypress" />
const dimensions = ["iphone-xr", "samsung-s10"];
context("check responsiveness", () => {
dimensions.forEach((dimension) => {
it("check responsiveness", () => {
cy.viewport(dimension); // <- error
});
});
});
Error that I'm getting: Argument of type 'string' is not assignable to parameter of type 'ViewportPreset'.ts(2345)
. I tried to do something like const dimensions : ViewportPreset[] = ["iphone-xr", "samsung-s10"];
but it response with Cannot find name 'ViewportPreset'.ts(2304)
. The only solution I currently have is to use any[]
but I think any
should be generally avoided since it removes all the benefits of TypeScript in first place. Also, if I add one of the dimensions manually to cy.viewport()
, even tho it's a string, I get no error.
CodePudding user response:
You can explicitly tell the callback that dimension
is a ViewportPreset.
Note small c on types="cypress" is the convention, but it does not seem to matter here.
Include the Cypress namespace in the type.
/// <reference types="cypress" />
context("check responsiveness", () => {
dimensions.forEach((dimension: Cypress.ViewportPreset) => {
it("check responsiveness", () => {
cy.viewport(dimension);
});
});
})
...
Also this works (instead of above)
const dimensions: Cypress.ViewportPreset[] = ['iphone-6', 'ipad-2']