zoukankan      html  css  js  c++  java
  • TestCafe 快速上手(一)

    TestCafe 版本: 1.9.2
    TestCafe 快速上手
    TestCafe 快速上手(一) - TestCafe API & Command Line Interface & Configuration File
    TestCafe 快速上手 (二) - Test API

    TestCafe API

    TestCafe Object

    Method Description
    createBrowerConnection 创建远程浏览器/手机 连接
    createRunner 创建用来配置和执行测试任务的runner
    createLiveModeRunner 创建live mode的runner
    close 停止TestCafe服务

    Global functions

    通过createTestCafe方法创建TestCafe实例
    async createTestCafe([hostname], [port1], [port2], [sslOptions], [developmentMode]) → Promise<TestCafe>
    Example

    const createTestCafe        = require('testcafe');
    const selfSignedSertificate = require('openssl-self-signed-certificate');
    
    const sslOptions = {
        key:  selfSignedSertificate.key,
        cert: selfSignedSertificate.cert
    };
    
    const testcafe = await createTestCafe('localhost', 1337, 1338, sslOptions);
    

    BrowerConnection Object

    首先为了连接到TestCafe服务,remoteConnection.url将会返回远程浏览器访问的网址url;
    当与远程浏览器建立连接,remoteConnection.ready事件被触发,在那之后你可以开始执行测试;

    const runner           = testcafe.createRunner();
    const remoteConnection = await testcafe.createBrowserConnection();
    
    // Outputs remoteConnection.url so that it can be visited from the remote browser.
    console.log(remoteConnection.url);
    
    remoteConnection.once('ready', () => {
        const failedCount = await runner
            .src('test.js')
            .browsers(remoteConnection)
            .run();
    
        console.log(failedCount);
        await testcafe.close();
    });
    

    LiveModeRunner Object

    live mode,testcafe 可以监控测试文件,当你修改保存文件后可以自动restart测试,也可以禁用监控。
    const runner = testcafe.createRunner();替换成const liveRunner = testcafe.createLiveModeRunner();即可。

    限制:一个testcafe只能创建一个文件监控系统来跟踪文件变化。

    • 你不能为testcafe server实例创建多个live mode runner
    • You cannot call the runner.run method more than once for a single LiveModeRunner.(不知道怎么翻译,大概意思就是一个live mode runner 不能调用多个runner.run)

    Runner Object

    const runner = testcafe.createRunner();
    注:

    • 由于命令行运行方式与此方法类似,熟悉此方法执行测试用例后即熟悉命令行执行,故不作赘述。可通过 testcafe -h获取相关命令行说明。
    • 部分选项此处未作说明,请查看 Configuration File 对应选项,此处仅贴代码演示。
      所有的配置选项都可以用 Configuration File 来配置。

    browsers

    指定浏览器,本地
    runner.browsers(['safari', 'chrome']);
    云浏览器
    runner.browsers('saucelabs:Chrome@52.0:Windows 8.1');
    指定路径浏览器

    runner.browsers('path:`C:\Program Files\Internet Explorer\iexplore.exe`');
    

    无头浏览器
    runner.browsers('chrome:headless');
    远程浏览器连接,见 BrowerConnection Object

    concurrency

    指定同时执行测试的浏览器实例
    runner.concurrency(3);

    filter 允许你选择执行的用例

    runner.filter((testName, fixtureName, fixturePath, testMeta, fixtureMeta) => {
        return fixturePath.startsWith('D') &&
            testName.match(someRe) &&
            fixtureName.match(anotherRe) &&
            testMeta.mobile === 'true' &&
            fixtureMeta.env === 'staging';
    });
    

    reporter

    reporter(name, output) → this
    reporter(fn) → this
    reporter([ name | { name, output } | fn ]) → this
    

    save the report to a File
    为了仅使用一个测试报告,指定??? 测试过后再添加该部分说明。
    runner.reporter('xunit', 'reports/report.xml');s

    run 运行参数

    runner.run({
           skipJsErrors: true,
           quarantineMode: true,
           selectorTimeout: 50000,
           assertionTimeout: 7000,
           pageLoadTimeout: 8000,
           speed: 0.1,
           stopOnFirstFail: true
       });
    

    screenshots

    runner.screenshots({
        path: 'reports/screenshots/',
        takeOnFails: true, //默认为false
        pathPattern: '${DATE}_${TIME}/test-${TEST_INDEX}/${USERAGENT}/${FILE_INDEX}.png',
        fullPage: true  //默认为false
    });
    

    Configuration File 配置文件

    创建 .testcaferc.json 配置文件来保存配置参数,将该文件放在你run testcafe的目录下,通常是根目录。
    以下为可配置项。

    browsers 指定浏览器及headless

    1. 指定本地浏览器执行用例
    # 只在chrome浏览器中执行用例
    "browsers": "chrome"  
    # 同时在ie,firefox执行用例
    "browsers": ["ie", "firefox"]
    # 指定浏览器执行用例
    "browsers": "path:`C:\Program Files\Internet Explorer\iexplore.exe`"
    
    1. 指定云端浏览器或非传统浏览器执行用例
      非传统浏览器插件
      由TestCafe团队提供的云端浏览器
      testcafe-browser-provider-saucelabs
      testcafe-browser-provider-browserstack
      你也可以自定义浏览器插件提供者
      "browsers": "saucelabs:Chrome@52.0:Windows 8.1"
    2. headless mode
      "browsers": ["firefox:headless", "chrome:emulation:device=iphone X"]

    src 指定测试用例目录/文件

    "src": "/home/user/tests/fixture.js"
    "src": ["/home/user/auth-tests/fixture.testcafe", "/home/user/mobile-tests/"]
    
    

    report 测试报告

    后面的Report模块将详细讲解如何使用
    指定测试报告输出,1.标准输出 2.形成文档;切记只有一个报告能采用第一个方法其他报告都要用第一个方法;

    "reporter": [
        {//方法1
            "name": "spec"
        },
        {//方法2
            "name": "json",
            "output": "reports/report.json"
        }
    ]
    

    screenshots 错误截屏

    后面的screenshots模块将详细讲解如何使用
    此参数为testcafe v1.5.0及更新版本适用

    "screenshots": {
            "path": "/home/user/tests/screenshots/", //图片保存路径
            "takeOnFails": true, //发生错误时截图
            "pathPattern": "${DATE}_${TIME}/test-${TEST_INDEX}/${USERAGENT}/${FILE_INDEX}.png", //也算路径吧,保存在path下
            "fullPage": true,
        }
    

    disableScreenshots 禁止截屏

    默认值:false
    "disableScreenshots": true
    开启该命令后,用例失败或者截屏命令执行时 不会截屏。

    screenshotPath

    此参数为testcafe v1.5.0之前的版本适用
    "screenshotPath": "/home/user/tests/screenshots/"

    takeScreenshotsOnFails

    此参数为testcafe v1.5.0之前的版本适用
    "takeScreenshotsOnFails": true

    screenshotPathPattern

    此参数为testcafe v1.5.0之前的版本适用
    "screenshotPathPattern": "${DATE}_${TIME}/test-${TEST_INDEX}/${USERAGENT}/${FILE_INDEX}.png"

    videoPath 视频地址

    "videoPath": "reports/screen-captures"
    

    videoOptions 视频选项

    "videoOptions": {
            "singleFile": true,
            "failedOnly": true,
            "pathPattern": "${TEST_INDEX}/${USERAGENT}/${FILE_INDEX}.mp4"
        }
    

    videoEncodingOptions 视频编码选项

    "videoEncodingOptions": {
            "r": 20,
            "aspect": "4:3"
        }
    

    quarantineMode 失败重试机制

    默认值:false
    失败 重试最多3次,若通过则不再重试

    debugMode

    感觉没啥用,还不如用LiveMode

    skipJsErrors 忽略JS错误

    默认值:false
    "skipJsErrors": true

    skipUncaughtErrors 忽略未抓取的错误

    忽略未抓取的错误和未处理的promise rejections, 默认值:false
    "skipUncaughtErrors": true

    filter

    允许你指定执行哪些用例或套件

    "filter": {
            "test": "Click a label", //指定执行用例名称为“Click a label”
            "testGrep": "Click.*", //指定执行用例名称包含”Click"
            "fixture": "Sample fixture", //指定执行套件名称为“Sample fixture”
            "fixtureGrep": "Page.*", //指定执行套件名称包含"Page"
            "testMeta": {
                "device": "mobile",
                "env": "production"
            }, //指定执行testMeta 中,device为mobile,env为production的用例
            "fixtureMeta": {
                "device": "mobile",
                "env": "production"
            } //指定执行fixtureMeta 中,device为mobile,env为production的套件
        }
    

    appCommand

    在开始测试之前执行指定的shell命令
    使用appCommand你可以开启你需要用来测试的app,并且在测试结束后会自动关闭。
    "appCommand": "node server.js"

    appInitDelay

    指定等待app开启允许的等待时间(毫秒),默认值为1000

    {
        "appCommand": "node server.js",
        "appInitDelay": 3000
    }
    

    concurrency

    指定同时执行测试的浏览器实例
    "concurrency": 3
    注意,Microsoft Edge不支持。

    selectorTimeout 元素等待时间

    指定等待找到元素的时间(毫秒),默认为10000
    "selectorTimeout": 3000

    assertionTimeout 断言成功时间

    指定等待断言成功的时间(毫秒),默认为3000
    "assertionTimeout": 1000
    指定assertionTimeout可以增加用例通过率

    pageLoadTimeout 页面加载时间

    指定等待DOM内容加载完成的时间(毫秒),默认为3000
    "pageLoadTimeout": 1000

    speed 测试执行速度

    指定测试执行速度。主要目的应该是检查是否某一个步骤没有执行导致用例失败(默认速度太快肉眼无法检查)
    "speed": 0.1
    默认速度为1,最慢 0.01,最快 1

    clientScripts

    由于目前不会使用到这一部分内容,后续若有需要另作说明。

    port1,port2

    指定测试用例执行的自定义端口,范围:0-65535

    "port1": 12345,
    "port2": 54321
    

    hostname

    指定电脑主机。

    proxy

    指定代理服务器。

    ssl

    你可以保证客户端和服务器的连接使用https,详细请看--ssl

    "ssl": {
        "pfx": "path/to/file.pfx",
        "rejectUnauthorized": true
    }
    

    developmentMode

    允许记录和报告错误。当你打算向TestCafe技术支持团队报告issue时
    "developmentMode": true

    qrCode

    不晓得有啥用

    stopOnFirstFail

    任意测试失败即停止所有测试, 默认值:false
    "stopOnFirstFail": true

    disablePageCaching

    默认值:false
    禁用页面缓存,当 测试结束后浏览器跳转到一个被缓存的页面的情况。比如使用role
    "disablePageCaching": true
    可用于fixture 或 test.

    disableMultipleWindows

    禁止chorme和firefox使用多窗口测试
    "disableMultipleWindows": true

    color , noColor

    允许命令行设置颜色 和禁用颜色

    "color": true
     "noColor": true
    

    Report

    testcafe-reporter-html

    安装依赖

    npm install testcafe-reporter-html
    

    输出报告

    runner

    const reportDir = "./reports/"+a+"result/report.html";
    runner.reporter("html", reportDir)
    

    命令行
    testcafe chrome test_folder/ --reporter html:path/to/my/file.html

    此外你也可以自定义report格式和内容:Reporter Plugin,后续有需要/有空再研究,用testcafe-reporter-html已经够用。

    截屏 screenshots

    测试用例执行失败时截屏

    1.命令行

    testcafe chrome ./ -s takeOnFails=true

    2.runner.screenshots

    runner.screenshots({
      takeOnFails:true
      });
    

    3.配置文件

    {
      "screenshots":{
        "takeOnFails":true
      }
    }
    

    截屏选项

    Option Type Description Default Value
    path String The base directory where screenshots are saved. ./screenshots
    takeOnFails Boolean true to take a screenshot whenever a test fails. false
    pathPattern String A pattern that defines how TestCafe composes the relative path to a screenshot file. See Screenshot and Video Directories. See Default Path Pattern.
    fullPage String true to capture the full page, including content that is not visible due to overflow. false

    截图文件名自定义参数

    Placeholder Description
    ${DATE} 测试开始日期
    ${TIME} 测试开始时间
    ${TEST_INDEX} The test's index.
    ${FILE_INDEX} The screenshot file's index.
    ${QUARANTINE_ATTEMPT} The quarantine attempt's number. If the quarantine mode is disabled, the ${QUARANTINE_ATTEMPT}
    ${FIXTURE} The fixture's name.
    ${TEST} 测试用例名称
    ${USERAGENT} 包含 ${BROWSER}, ${BROWSER_VERSION}, ${OS}, and ${OS_VERSION} (separated by underscores).
    ${BROWSER} 浏览器名称
    ${BROWSER_VERSION} 浏览器版本
    ${OS} 操作系统名称
    ${OS_VERSION} 操作系统版本
    ${TEST_ID} Resolves to test-${TEST_INDEX} if TestCafe can associate this screenshot or video with a specific test; resolves to an empty string otherwise (for instance, when a single video is recorded for the entire test run).
    ${RUN_ID} Resolves to run-${QUARANTINE_ATTEMPT} for screenshots taken when quarantine mode is enabled; resolves to an empty string for videos and for screenshots taken when quarantine mode is disabled.

    录屏

    注意:录屏只允许在谷歌浏览器,火狐浏览器,edge浏览器,当你使用远程浏览器测试时无法录屏

    安装软件 FFmpeg library

    use

    1.命令行

    testcafe chrome ./ --video artifacts/videos

    2.runner.screenshots

    runner.video('artifacts/videos');
    

    3.配置文件

    {
      "videoPath":"artifacts/videos"
    }
    

    录屏选项

    Option Type Description Default Value
    failedOnly Boolean 默认为false,当为true时只记录失败的用例。 false
    singleFile Boolean 默认为false,当为true时所有录屏在同一个MP4文件 false
    ffmpegPath String The path to the FFmpeg codec executable. Auto-detected
    pathPattern String A pattern that defines how TestCafe composes the relative path to a video file. See Screenshot and Video Directories. See Default Path Pattern.

    写在最后

    笔记完全根据个人理解,如与实际实现有出入,望指出。

  • 相关阅读:
    【BZOJ 3090】 树形DP
    【BZOJ 2323】 2323: [ZJOI2011]细胞 (DP+矩阵乘法+快速幂*)
    【BZOJ 1019】 1019: [SHOI2008]汉诺塔 (DP?)
    【BZOJ 3294】 3294: [Cqoi2011]放棋子 (DP+组合数学+容斥原理)
    【BZOJ 3566】 3566: [SHOI2014]概率充电器 (概率树形DP)
    【BZOJ 2121】 (字符串DP,区间DP)
    【BZOJ 4305】 4305: 数列的GCD (数论)
    【UOJ 179】 #179. 线性规划 (单纯形法)
    【BZOJ 4568】 4568: [Scoi2016]幸运数字 (线性基+树链剖分+线段树)
    【BZOJ 4027】 4027: [HEOI2015]兔子与樱花 (贪心)
  • 原文地址:https://www.cnblogs.com/Tester_Dolores/p/13926205.html
Copyright © 2011-2022 走看看