TestCafe 1 入门

开始

关于本文

本文面向TestCafe 0基础的读者。需要熟悉JavaScript, web,命令行的基本操作。

TestCafe是什么

TestCafe 是适用于 web 应用 的一款 end-to-end 测试框架。基于 Node.js 运行。支持三大主流操作系统,Linux, Windows 以及 macOS。
你可以用 TestCafe 模拟在桌面浏览器,云浏览器和移动设备上一般用户场景。
当你的网站出问题时,也能用 TestCafe报告 来定位问题。

安装 TestCafe

1. Node.js

https://nodejs.org/en

image

安装好后能查到版本号,说明已经正确安装

node --version

image

2. 安装testcafe

npm install -g testcafe

image

Demo

创建一个测试

fixture('Getting Started')
    .page('https://www.baidu.com');

test('My first test', async t => {
    // Test code goes here
});

增加测试行为

1. 输入文本

await t.typeText('#developer-name', 'John Smith');

2. 点击按钮

await t.click('#submit-button');

完整代码

fixture('Getting Started')
    .page('https://devexpress.github.io/testcafe/example');

test('My first test', async t => {
    await t
        .typeText('#developer-name', 'John Smith')
        .click('#submit-button');
});

增加成功条件

1. 创建一个assertion

这里是对比x和y

await t.expect(x).eql(y);

2. 明确实际值

在文件开头导入 Selector 类

import { Selector } from 'testcafe';

在assertion左边加上Selector 查询

await t.expect(Selector('#article-header').innerText).eql(y);

3. 明确期望值

await t.expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');

4. 完整代码

import { Selector } from 'testcafe';

fixture('Getting Started')
    .page('https://devexpress.github.io/testcafe/example');

test('My first test', async t => {
    await t
        .typeText('#developer-name', 'John Smith')
        .click('#submit-button')
        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');
});

运行

testcafe chrome getting-started.js

在这一步我遇到了报错:client.Fetch.continueResponse is not a function
image

更新Chrome到最新成功解决。

image

可选: 激活热重载

testcafe chrome getting-started.js --live

在 TestCafe 运行测试时,你可以与其他应用程序进行交互。
但是,不要切换到运行测试的浏览器标签页之外,也不要最小化浏览器窗口。
非活动标签页和最小化的浏览器窗口可能会触发资源节省模式,从而影响测试性能。
测试期间请勿缩放页面。放大或缩小页面可能会导致测试失去稳定性。

posted @ 2026-03-04 10:07  HarryMiau  阅读(32)  评论(0)    收藏  举报