I am finding the typescript support in Cypress is a bit confusing. I was able to achieve correct typing for my custom commands fairly easily. However, I am struggling to get it working with plugins.
For example, if I have this simple plugins/index.ts
file.
import { generateEmail } from "./my-temp-mail-file"
const pluginConfig = async (on, config) => {
on("task", {
generateEmail: async () => {
const email = await generateEmail()
return email
}
})
}
export default pluginConfig
The on, config
are always undefined types (ie Parameter 'on' implicitly has an 'any' type
). Even if I include the type declaration suggested by Cypress it doesn't help.
When I try to use my custom plugins, the return argument available in the then
method is always unknown
.
For example email
is always unknown`.
cy.task("generateEmail").then(email => {
///...do something
})
At the moment I am importing my types, and this works but a little annoying.
cy.task("generateEmail").then((email: string) => {
///...do something
})
Is there a way I can have them automatically there like I can with commands?
CodePudding user response:
You can see the types for on, config
by hovering Cypress.PluginConfig
, but admittedly the annotation should be kicking in.
If generateEmail()
has a return type, it will be inferred in the task
/**
* @type {Cypress.PluginConfig}
*/
export default (on: Cypress.PluginEvents, config: Cypress.PluginConfigOptions) => {
on("task", {
generateEmail: async () => {
const email = await generateEmail() // type shows "const email: string"
return email
}
})
}
function generateEmail(): Promise<string> {
return Promise.resolve('z')
}
To type the task return value in the test, add this to plugins
declare global {
namespace Cypress {
interface Chainable {
task(event: 'generateEmail'): Chainable<string>;
}
}
}
cy.task('generateEmail').then(email => { // type shows "(parameter) email: string"
...
})