Cypress自定义查找命令不可链接



我想创建一个自定义的Cypressfind命令,这样可以利用data-test属性。

柏树/支撑/指数.ts

declare global {
namespace Cypress {
interface Chainable {
/**
* Custom command to get a DOM element by data-test attribute.
* @example cy.getByTestId('element')
*/
getByTestId(selector: string): Chainable<JQuery<HTMLElement>>;
/**
* Custom command to find a DOM element by data-test attribute.
* @example cy.findByTestId('element')
*/
findByTestId(selector: string): Chainable<JQuery<HTMLElement>>;
}
}
}

柏树/支持/命令。ts

Cypress.Commands.add('getByTestId', (selector, ...args) => {
return cy.get(`[data-test=${selector}]`, ...args);
});
Cypress.Commands.add(
'findByTestId',
{ prevSubject: 'element' },
(subject, selector) => {
return subject.find(`[data-test=${selector}]`);
}
);

这里subject的类型是JQuery<HTMLElement>而不是Cypress.Chainable<JQuery<HTMLElement>>,因此subject.find不能与其他方法链接。

我从Typescript中得到以下错误。

No overload matches this call.
Overload 1 of 4, '(name: "findByTestId", options: CommandOptions & { prevSubject: false; }, fn: CommandFn<"findByTestId">): void', gave the following error.
Overload 2 of 4, '(name: "findByTestId", options: CommandOptions & { prevSubject: true | keyof PrevSubjectMap<unknown> | ["optional"]; }, fn: CommandFnWithSubject<"findByTestId", unknown>): void', gave the following error.
Overload 3 of 4, '(name: "findByTestId", options: CommandOptions & { prevSubject: "element"[]; }, fn: CommandFnWithSubject<"findByTestId", JQuery<HTMLElement>>): void', gave the following error.ts(2769)
cypress.d.ts(22, 5): The expected type comes from property 'prevSubject' which is declared here on type 'CommandOptions & { prevSubject: false; }'

所需用途

cy.getByTestId('some-element')
.findByTestId('some-test-id')
.should('have.text', 'Text');

我该怎么解决这个问题?

您的commands文件会有这样的命令。请注意,这将记录cy.wrap,如果您选择的话,您可能需要传递log: false来抑制它。您还可以添加另一个agrument,并为文本提供一个if块,以便将data-testid.contains()一起使用

Cypress.Commands.add(
'byTestId',
{ prevSubject: 'optional' },
(subject, id) => {
if (subject) {
return cy.wrap(subject).find(`[data-testid="${id}"]`)
}
return cy.get(`[data-testid="${id}"]`)
},
)

这将是命令的应用程序。

cy.byTestId('first-id')
// maybe some assertions here for visibility check
.byTestId('id-inside-first-element')
// maybe some assertions here for visibility check
.byTestId('id-within-this-second-element')

I可能偏离了目标,但subject.find(...)正在使用jQuery find。

也许您想要cy.wrap(subject).find(...),它应该产生Cypress.Chainable包装器。

必须像这样在JQuery元素周围添加一个cy.wrap命令。

Cypress.Commands.add(
'findByTestId',
{ prevSubject: 'element' },
(subject, selector) => {
return cy.wrap(subject).find(`[data-test=${selector}]`);
}
)

最新更新