你应该如何构建 CRUD cypress 测试?

How should you structure CRUD cypress tests?

我正在开发 React 应用程序,我们的团队正在为其编写 Cypress 测试。我们想测试基本的 CRUD 功能,所以我们创建了三个测试:

CREATE 测试使用夹具来定义新用户。

UPDATE 和 DELETE 测试引用相同的装置并更新和删除在先前测试中创建的用户。这意味着 UPDATE 和 DELETE 测试依赖于 CREATE 测试。这样可以吗?

根据我正在阅读的内容,听起来每个 Cypress 测试都应该能够 运行 独立,我可以看出这里不是这种情况。

但是,最好的方法是什么?

我认为从 CREATE 测试中复制和粘贴相同的 10-20 行代码并在 UPDATE 和 DELETE 测试中复制它们没有意义。有没有一种方法可以抽象 CREATE 测试并将其包含在 UPDATE 和 DELETE 测试中?

或者我们应该将所有三个测试组合成一个“CRUD 用户”测试吗?

Based on what I'm reading, it sounds like each Cypress test should be able to run independently.

理想情况下,是的。有几个原因:

  • 理论上,如果一个测试失败,其他测试仍然可以通过;但是如果你创建某个实体(在你的例子中是用户)的测试失败了,其他的肯定会失败,但不是因为他们关注的是什么
  • 你真的没有办法确保测试以相同的顺序执行;尽管在 Cypress 中,我认为它是基于字母顺序的,但这可能不适用于其他工具,甚至将来也不适用于 Cypress;或者你决定在某个地方添加一些测试,这会改变测试的顺序,突然间一些测试会失败,你不会立即知道为什么

I don't think it makes sense to copy and paste the same 10-20 lines of code from the CREATE test and duplicate them in both the UPDATE and DELETE tests. Is there a way we can abstract the CREATE test and include it in the UPDATE and DELETE tests?

Cypress 提供了示例 commands,因此您的最终测试代码可能如下所示:

it('CREATE user', () => {
  cy
    .fixture('user')
    .then(user => {
      cy
        .createUser(user)
        // whatever checks you need to perform here
        .its('response.statusCode')
        .should('eq', 201); 
    });
});

那么如果你的 10-20 行代码隐藏在 cy.createUser() 后面,你可以很容易地在其他测试中重用它:

it('DELETE user', () => {
  cy
    .fixture('anotherUser')
    .then(anotherUser => {
      cy
        .createUser(anotherUser)
        .then(response => {
          cy
            .deleteUser(response.body.id)
            // whatever checks you need to perform
            .its('response.statusCode')
            .should('eq', 204);
        });
    });
});

我认为这样的代码很容易阅读并且测试也很短,因此如果需要的话很容易维护。