Cypress脚本baseUrl判断报错:TypeError: baseUrl.contains is not a function
解决Cypress中baseUrl字符串判断的TypeError问题
你遇到的TypeError: baseUrl.contains is not a function错误,原因是JavaScript原生字符串没有contains()方法——这个方法属于jQuery或DOM元素的API,不能直接用于普通字符串。
以下是两种正确的字符串包含判断实现方式:
方法1:使用ES6的includes()方法(推荐)
includes()是ES6新增的字符串方法,直接返回布尔值,语法简洁直观:
const baseUrl = Cypress.config('baseUrl'); if (baseUrl.includes('localhost')) { // 执行localhost环境对应的逻辑 } else { // 执行其他环境对应的逻辑 }
方法2:使用兼容旧环境的indexOf()方法
如果需要兼容不支持ES6的环境,可以用indexOf()——当子串存在时返回其起始索引,不存在则返回-1:
const baseUrl = Cypress.config('baseUrl'); if (baseUrl.indexOf('localhost') !== -1) { // 执行localhost环境对应的逻辑 } else { // 执行其他环境对应的逻辑 }
额外注意事项
为避免baseUrl为null或undefined时触发报错,可添加前置判断:
const baseUrl = Cypress.config('baseUrl'); if (baseUrl && baseUrl.includes('localhost')) { // 逻辑代码 } else { // 逻辑代码 }
内容的提问来源于stack exchange,提问作者Carrie Kaski
相关产品推荐
相关产品推荐

