我想像這樣創建一個自定義賽普拉斯find命令來利用一個data-test屬性。
賽普拉斯/支持/index.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>>;
}
}
}
賽普拉斯/支持/commands.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是 typeJQuery<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');
我該如何解決這個問題?
uj5u.com熱心網友回復:
我可能不合時宜,但subject.find(...)使用的是 jQuery 查找。
也許您想要cy.wrap(subject).find(...)哪個應該產生 Cypress.Chainable 包裝器。
uj5u.com熱心網友回復:
你的commands檔案會有這樣的命令。log: false請注意,這將記錄 cy.wraps ,如果您選擇,您可能希望通過來抑制它。您還可以添加另一個 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')
uj5u.com熱心網友回復:
cy.wrap必須像這樣在 JQuery 元素周圍添加一個命令。
Cypress.Commands.add(
'findByTestId',
{ prevSubject: 'element' },
(subject, selector) => {
return cy.wrap(subject).find(`[data-test=${selector}]`);
}
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/437528.html
標籤:javascript jQuery 打字稿 测试 柏
