我有一个方法可以获取元素hrefAppTheme
的href属性,并判断它是否是字符串数组appThemes
的值之一:
describe('...',() => {
it('should ...', () => {
(...)
let defaultAppTheme = '';
onMenuPage.hrefAppTheme.invoke('attr', 'href')
.then(hrefVal => {
if (typeof hrefVal !== 'undefined') {
expect(hrefVal).to.be.oneOf(onMenuPage.appThemes);
defaultAppTheme = hrefVal;
//referencing the variable 'defaultAppTheme' further below...
}
});
可以肯定地认为,this.hrefAppTheme.invoke('attr', 'href')
总是返回一个用户主题(一个字符串),因为上面的代码工作可靠.
因为我需要在几个不同的地方使用该逻辑,所以我想将其提取到一个方法中,并将其放入页面对象类中.这就是我所得到的:
export default class MenuPage {
(...)
getUserTheme(): string {
let userTheme = '';
cy.then(() => {
this.hrefAppTheme.invoke('attr', 'href')
.then(resVal => {
if (typeof resVal !== 'undefined') {
userTheme = resVal;
}
});
});
return userTheme;
}
我认为我需要使用cy.wrap()
方法来赋值要返回的字符串:
describe('...',() => {
it('should ...', () => {
(...)
let defaultAppTheme = '';
cy.wrap(onMenuPage.getUserTheme()).then(resVal => {
defaultAppTheme = resVal;
expect(defaultAppTheme).to.be.oneOf(onMenuPage.appThemes);
});
//referencing the variable 'defaultAppTheme' further below...
然而,这是有问题的,因为返回的值始终是空字符串,而不是解析值:
AssertionError: expected '' to be one of [ 'theme-light.css', 'theme-dark.css' ]
+ expected - actual
+[ 'theme-light.css', 'theme-dark.css' ]
如何返回Resolve-Value myWebelement.invoke('attr', 'href').then(hrefVal => {
(...),以及如何通过调用此方法将其赋给变量?
或者,有没有更好的方法将工作代码提取到方法中?