You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebdriverIO+Appium测试报错:expect(...).toHaveTextContaining不是函数

问题解决与答疑

一、toHaveTextContaining 报错解决

你遇到的 TypeError: expect(...).toHaveTextContaining is not a function 报错,是因为WebdriverIO v8+版本调整了断言API,toHaveTextContaining 方法已被移除,有两种替代方案:

方案1:用toHaveText结合字符串匹配器

修改断言代码为:

await expect(subtitleTxt).toHaveText(expect.stringContaining('automation'));

方案2:先获取文本再断言

直接拿到元素文本后用基础断言方法:

const text = await subtitleTxt.getText();
await expect(text).toContain('automation');

二、关于@wdio/globals导入的疑问

是的,WebdriverIO从v7版本开始,默认不再把$、expect、driver等核心对象挂载到全局作用域,必须显式从@wdio/globals导入才能正常使用。

你之前不需要导入是因为用的是v6及更早版本,旧版本默认将这些对象全局化。新版本做这个变更的目的是减少全局变量污染,让代码结构更清晰规范。如果实在不想每次手动导入,可以在wdio.conf.js配置文件中开启全局挂载:

exports.config = {
  // 其他配置项...
  globals: {
    $: true,
    $$: true,
    expect: true,
    driver: true
  }
}

不过官方更推荐显式导入的方式,避免潜在的全局变量冲突问题。


附你提供的报错信息:
[wdiodemoapp.app iOS #0-0] XXX App
[wdiodemoapp.app iOS #0-0] ✖ ios Testing
[wdiodemoapp.app iOS #0-0]
[wdiodemoapp.app iOS #0-0] 1 failing (2.7s)
[wdiodemoapp.app iOS #0-0]
[wdiodemoapp.app iOS #0-0] 1) Expense App ios Testing
[wdiodemoapp.app iOS #0-0] expect(...).toHaveTextContaining is not a function
[wdiodemoapp.app iOS #0-0] TypeError: expect(...).toHaveTextContaining is not a function
[wdiodemoapp.app iOS #0-0] at Context. (file:///Users/xxx.xxx//test/specs/demo.js:25:30)

你的测试代码:

import { $, expect, driver } from '@wdio/globals';

describe('Expense App', ()=>{

it ('ios Testing ', async () =>{

  await $("~Webview").click();

  //1. get your multiple contexts with this code 
  await driver.waitUntil(async () =>{
      const contexts = await driver.getContexts();
      return contexts.length >1;
    }, {timeout: 30000,
        timeoutMsg: 'Sorry, its taking so long. Waiting for another context'});

   //2. Switch to webdrive context 

   const contexts = await driver.getContexts();
   await driver.switchContext(contexts[1])

   //3. Confirm webview context 
   const subtitleTxt = await $('.hero_subtitle');
   await expect(subtitleTxt).toHaveTextContaining('automation');
});
});

内容的提问来源于stack exchange,提问作者fypnlp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 03:07:21