ercos / cakephp-cypress
cypress控制器集成,用于处理身份验证和数据库数据
v1.0.2
2023-05-09 06:48 UTC
Requires
- php: >=8.0.8
- cakephp/cakephp: >=4.2
Requires (Dev)
README
此包允许您在CakePHP项目中使用工厂和固定值运行Cypress测试,并受Laravel Cypress包的启发。
要求
- CakePHP 4.0+
- Cypress 10.0+
- PHP 8.0+
- https://github.com/josegonzalez/php-dotenv
- 强烈推荐使用https://github.com/vierge-noire/cakephp-fixture-factories 来充分利用此包
API设置
- 安装包:
composer require ercos/cakephp-cypress - 在
src/Application.php文件中加载插件:bin/cake plugin load Ercos/CakephpCypress - 将数据库结构(所有表 + phinxlog结构 + 数据)提取为SQL文件。
- 将SQL文件添加到您的项目中,例如在
/dump/my-database.sql中。 - 将
config/.env复制到config/.env.cypress。 重要:请确保在DB_DATABASE(默认)和DB_TEST_DATABASE(测试)环境变量中设置测试数据库。 在
config/.env.cypress文件中添加SQL文件的路径,如下所示:export SQL_DUMP_FOLDER="/dump/my-database.sql"在您的
.htaccess文件中添加以下代码
RewriteEngine On
SetEnvIf x-cypress-header true cypress
...
这将允许插件检测请求是否来自Cypress,并自动切换到测试数据库(根据.env.cypress)
- 在您的
config/bootstrap.php文件中,添加逻辑以在请求来自Cypress时加载.env.cypress文件。您应该在config/bootstrap.php文件中的导入之后找到要更新的代码部分。
if (!env('APP_NAME')) {
$dotenv = '';
if (env('cypress') && file_exists(CONFIG . '.env.cypress')) {
$dotenv = new Loader([CONFIG . '.env.cypress']);
} elseif (file_exists(CONFIG . '.env')) {
$dotenv = new Loader([CONFIG . '.env']);
}
if ($dotenv instanceof Loader) {
$dotenv->parse()
->toEnv();
}
}
- 在您的
src/Application.php中,在bootstrap()函数中添加以下代码
if (env('cypress')) {
require TESTS . 'bootstrap.php';
}
- 在您的
tests/bootstrap.php文件中,当Cypress运行时不要导入bootstrap.php文件,如下所示
if (!env('cypress', false)) {
require dirname(__DIR__) . '/config/bootstrap.php';
}
- 在您的
tests/bootstrap.php文件中,添加以下代码以修复会话的使用。
由于php7.2+不允许在stdout写入后设置sessionid,因此请尽早固定sessionid。if (!env('cypress', false)) { session_id('cli'); }
前端设置
npm install cypress --save-dev- 将
front-end文件夹的内容复制到前端项目的根目录。 - 更新Cypress配置(根据您的Cypress版本,请使用
cypress.json或cypress.config.ts文件作为示例) - 将固定值添加到
tests/cypress/support/commands.js中,以启用数据库刷新命令
body: {
fixtures: [
"app.Users",
...
]
},
可用命令
refreshDatabase:在Cypress before钩子中调用。此命令删除所有表,执行SQL文件以创建新的数据库,并最后运行迁移。您可以不时更新该文件以加快测试设置时间。create:使用工厂在数据库中创建记录。例如,cy.create('Users', { username: 'John' })将创建用户名为"John"的用户。login:登录用户。您需要完成tests/cypress/support/commands.js中的login函数,使其与您的前端项目一起工作。
用法
- 在
tests/cypress/integration文件夹中创建测试 - 运行
npx cypress open