使用Cypress测试Laravel Breeze身份验证

这篇文章展示了一些例子, 这些例子很容易添加到任何使用Laravel Breeze的Laravel项目中.

为了使用完整的例子, 你应该要求使用Laracast/Cypress包。

Laravel Cypress集成这个软件包提供了必要的模板,以快速开始使用Cypress测试你的Laravel应用程序。


github:

https://github.com/laracasts/cypress


这里有一个登录的例子:

请记住, Laravel的默认用户工厂将工厂生成的用户密码设置为 "password":

describe('Authentication test', () => {
    it('测试一个成功的手动认证的登录表格', () => {
        cy.visit(`/login`);
        cy.php(`
            App\\Models\\User::factory()->create(['email', '[email protected]']);
        `).then(user => {
            cy.get('input[type="email"]').type(user.email);
            cy.get('input[type="password"]').type('password');
        });
        cy.get('button[type="submit"]').click();
        cy.location('pathname').should('equal', '/dashboard');
    });
});


一些代码示例:

1.测试http状态代码

cy.request('http://localhost:8000/dashboard').then((response) => expect(response.status).to.eq(200));


2.测试一个中间件

// visit a url
cy.visit('http://localhost:8000/dashboard');
// check the next url location
cy.url().should('match', /login);

有时你需要测试一个较大的工作流程,如注销,然后检查一些中间件是否工作...

cy.visit('/logout') //我为你准备了封面,它将会带来神奇的效果


3.检查一些内容

请记住,你应该避免测试可能被转义的文本,

因此,你可以测试一些像/dashboard url中的欢迎信息。

cy.contains('Welcome');

或者更好的是,使用PHP方法或登录助手来准确测试当前用户的欢迎信息。

cy.login({ email: '[email protected]', name: 'John Doe' });
cy.visit('/dashboard').contains('Welcome Back, John Doe');

希望这个小例子能够帮助到你,

为你的应用程序创建自己的测试。

相关文章