AI 动力前端测试:如何更快地编写更智能的测试

利用ChatGPT来简化您的前端测试流程并提高覆盖范围。

AI-generated image if robot hand holding a stylus to a futuristic looking chalkboard with a vibrant cityscape in the background
what i imagine when i ask ai to write test cases for me for the billionth time

在快节奏的前端开发世界中,保持高质量标准至关重要。如果你曾经面临过需要在短时间内迅速增加测试覆盖率的不幸任务,你可能会对前端测试的重复性、令人厌烦和耗时有所了解。

```html

为了克服这一挑战,我最近开始利用我们未来的AI霸主,让它为我做繁重的工作。

```

所以,这是我关于工程师如何利用诸如ChatGPT这样的人工智能工具来革新前端测试方法、简化工作流程并改进测试覆盖范围的小Ted演讲文章。

前端测试实践

一个健壮的前端测试策略对于确保全面的覆盖和高质量至关重要。一个典型的测试结构可能包括以下组件:

  • Sure, here's how you could structure and translate that sentence into simplified Chinese, while maintaining HTML-like tags for clarity: ```html UI组件:用户界面的核心构建块,通常使用像React和Vue这样的框架构建(或者如果你喜欢挑战,甚至可以使用Knockout.JS)。 ``` In this translation: - **UI组件** stands for "UI components." - **用户界面的核心构建块** means "the core building blocks of the user interface." - **通常使用像React和Vue这样的框架构建** translates to "often built using frameworks like React and Vue." - **(或者如果你喜欢挑战,甚至可以使用Knockout.JS)** provides an optional suggestion, "or maybe even Knockout.JS if you like a challenge." This structure keeps the translation faithful to the original sentence while incorporating HTML tags for clarity in a technical context.
  • 存储器和呈现器:管理状态(存储)和处理逻辑(呈现)的类。将其想象为UI组件的大脑。
  • 单元测试:用于测试单独的组件和功能。
  • 集成测试: 用于验证组件之间的完整流程和交互。这是我们确保个别组件通过用户流程按预期交互的地方。
  • E2E测试:非常昂贵但非常有价值的自动化测试,用于测试用户故事的端到端流程。端到端测试指从服务器到客户端。

这篇文章将着重介绍为UI组件、存储器和展示器生成单元测试。在代码示例中,我将使用JavaScript/TypeScript混合实现React,使用MobX作为状态管理。测试代码将利用Jest,这是一个用于JavaScript的测试工具。

Sure, here is the translation of "Generating unit test cases with GPT" in simplified Chinese, while keeping the HTML structure intact: ```html 生成单元测试案例与GPT ``` This HTML snippet preserves the structure while presenting the translated text in simplified Chinese.

Certainly! Here's the translated text in simplified Chinese, preserving the HTML structure: ```html

创建广泛的单元测试可能会令人望而生畏,尤其是在试图涵盖各种场景时。虽然测试驱动开发(TDD)是理想的,但产品开发的残酷现实是,事物变化迅速,转眼之间就会发生变化。不幸的是,当加快速度时,测试几乎总是第一个被牺牲的。

``` This HTML snippet contains the translated text in simplified Chinese within a `

` (paragraph) element, as requested.

Sure, here's the translation of your text into simplified Chinese, maintaining the HTML structure: ```html 幸运的是,我那个焦虑的完美主义者自己并不总是让我接受随意做事的念头,听了一些同事对他们一直在使用的所有 GPT 都赞不绝口后,我决定试一试。 ``` This translation captures the meaning while preserving the structure suitable for HTML rendering.

感谢上帝,因为人工智能已被证明是我有过的最好的编码伙伴——部分原因是在我要求它简化解释时没有评判,部分原因是在帮助我编写测试时拥有的巨大力量和速度!

自动化测试用例生成.

通过直接将组件代码输入ChatGPT,我们可以快速生成大量的测试用例,覆盖各种潜在场景。

Certainly! Here is the translation of the text into simplified Chinese while keeping the HTML structure intact: ```html

这里是一个非常基础的按钮组件示例,可以用来生成测试:

``` This HTML snippet maintains the structure while providing the translated text in simplified Chinese.
// Button.js

import React from 'react';

const Button = ({ onClick, label }) => (
<button onClick={onClick}>{label}</button>
);

export default Button;

提示:“为这个React按钮组件生成单元测试。测试应该检查按钮是否正确渲染以及点击按钮时是否调用了onClick处理程序。”

生成單元測試:

// Button.test.js
import { render, fireEvent } from '@testing-library/react';
import Button from './Button';

test('renders button with label', () => {
const { getByText } = render(<Button label="Click Me" />);
const buttonElement = getByText(/Click Me/i);
expect(buttonElement).toBeInTheDocument();
});

test('calls onClick handler when clicked', () => {
const handleClick = jest.fn();
const { getByText } = render(<Button label="Click Me" onClick={handleClick} />);
const buttonElement = getByText(/Click Me/i);
fireEvent.click(buttonElement);
expect(handleClick).toHaveBeenCalledTimes(1);
});

Sure, here's the simplified Chinese translation of "Look at all of that perfectly generated code!" while keeping the HTML structure: ```html 看那些完美生成的代码! ```

Certainly! Here's the translation of "Expediting test creation" into simplified Chinese while keeping the HTML structure: ```html 加速测试创建 ``` This HTML snippet preserves the structure while presenting the translated text in simplified Chinese characters.

这种自动化可以减少编写重复测试所需的时间,并确保覆盖更多边缘案例。一旦你编写了足够多的测试,通常可以利用ChatGPT来为您“完成剩下的部分”,使用您现有测试中的相同模式。

Sure, here's how you could structure the HTML while incorporating the translation: ```html

Translated Content

使用生成的单元测试,我们可以礼貌地要求ChatGPT进一步扩展:

``` In this HTML structure: - `lang="zh-Hans"` specifies Simplified Chinese as the language. - The `` tag ensures proper encoding for Chinese characters. - The text "使用生成的单元测试,我们可以礼貌地要求ChatGPT进一步扩展:" is the translated content within the `

` tag.

Certainly! Here's the translated text in simplified Chinese, keeping the HTML structure intact: ```html

提示:“为以下按钮组件扩展测试用例,覆盖更多边缘情况和场景。现有测试包括渲染、基本点击处理和禁用状态。请包括不同按钮类型、空标签的测试,并确保按钮类型属性的正确性。”

``` This HTML snippet contains the translated prompt in simplified Chinese within a paragraph (`

`) tag.

Sure, here's the translated text in simplified Chinese, keeping the HTML structure: ```html

生成额外的案例:

``` This HTML code maintains the structure while displaying the translated text "生成额外的案例:" which means "Additional cases generated:".
test('button is disabled when disabled prop is true', () => {
const { getByText } = render(<Button label="Click Me" disabled={true} />);
const buttonElement = getByText(/Click Me/i);
expect(buttonElement).toBeDisabled();
});

test('button is enabled when disabled prop is false', () => {
const { getByText } = render(<Button label="Click Me" disabled={false} />);
const buttonElement = getByText(/Click Me/i);
expect(buttonElement).toBeEnabled();
});

test('renders button with different types', () => {
const { getByRole } = render(<Button label="Submit" type="submit" />);
const buttonElement = getByRole('button', { name: /Submit/i });
expect(buttonElement).toHaveAttribute('type', 'submit');

render(<Button label="Reset" type="reset" />);
const resetButtonElement = getByRole('button', { name: /Reset/i });
expect(resetButtonElement).toHaveAttribute('type', 'reset');
});

test('renders button with empty label', () => {
const { container } = render(<Button label="" />);
const buttonElement = container.querySelector('button');
expect(buttonElement).toHaveTextContent('');
});

test('ensures button type is default button', () => {
const { getByRole } = render(<Button label="Default" />);
const buttonElement = getByRole('button', { name: /Default/i });
expect(buttonElement).toHaveAttribute('type', 'button');
});

礼貌是关键——我对我Google Home Mini已经够刻薄了,当AI接管发生时,我肯定是第一个被淘汰的¯\_(ツ)_/¯.

增强现有组件的覆盖范围

随着我们代码库的发展,我们的测试也必须跟着发展。ChatGPT帮助我们增强对现有组件的覆盖范围。

Sure, here is the translation of "Analyzing Existing Tests" in simplified Chinese while keeping the HTML structure intact: ```html 分析现有测试 ```

AI可以审查当前的测试用例,并确定是否有任何遗漏的场景或漏洞。

Certainly! Here's the translation in simplified Chinese while keeping the HTML structure: ```html

考虑到这个基本的存储器用于计数器功能及其现有的测试:

``` This HTML snippet maintains the structure while presenting the translated text in simplified Chinese.
// CounterStore.ts
import { makeAutoObservable } from 'mobx';

class CounterStore {
count: number = 0;

constructor() {
makeAutoObservable(this);
}

increment() {
this.count += 1;
}

decrement() {
this.count -= 1;
}

reset() {
this.count = 0;
}
}

export default new CounterStore();
// CounterStore.test.ts
import CounterStore from './CounterStore';

describe('CounterStore', () => {
let store: CounterStore;

beforeEach(() => {
store = new CounterStore();
});

test('initial state', () => {
expect(store.count).toBe(0);
});

test('increment method increases count by 1', () => {
store.increment();
expect(store.count).toBe(1);
});

test('decrement method decreases count by 1', () => {
store.increment(); // Increase count first
store.decrement();
expect(store.count).toBe(0);
});

test('reset method sets count to 0', () => {
store.increment(); // Increase count first
store.reset();
expect(store.count).toBe(0);
});
});

让我们请求ChatGPT识别任何缺失的场景并加以实施:

Sure, here's the translated text in simplified Chinese, while keeping the HTML structure: ```html

提示:这里是 CounterStore 的现有单元测试。请仔细审阅它们,并提出额外的测试场景或修改建议,以确保全面覆盖。该存储包括增加、减少和重置计数器的方法。

``` In Chinese: ```html

提示:这里是 CounterStore 的现有单元测试。请仔细审阅它们,并提出额外的测试场景或修改建议,以确保全面覆盖。该存储包括增加、减少和重置计数器的方法。

``` This HTML structure preserves the content while displaying it in a web context.

Sure, here's the translation of "Generated suggestions for additional coverage:" in simplified Chinese while maintaining the HTML structure: ```html 生成的额外覆盖建议: ``` This preserves the HTML tags around the translated text for proper integration into your web page.

1. 测试大量增量:

test('increment method handles large numbers', () => {
store.count = Number.MAX_SAFE_INTEGER - 1;
store.increment();
expect(store.count).toBe(Number.MAX_SAFE_INTEGER);
});

Certainly! Here is the translation of "2. Test Decrement Below Zero:" in simplified Chinese, keeping the HTML structure intact: ```html 2. 测试减少到零以下: ``` This text will appear in your HTML document as numbered text in simplified Chinese.

test('decrement method handles values below zero', () => {
store.decrement();
expect(store.count).toBe(-1);
});

3. 测试多个连续操作:

test('multiple sequential operations', () => {
store.increment();
store.increment();
store.decrement();
store.reset();
expect(store.count).toBe(0);
});

4. 在先前增量的情况下进行测试重置。

test('reset method called without increment', () => {
store.reset();
expect(store.count).toBe(0);
});

看看那些我们没必要自己考虑的边缘情况!

Certainly! Here's the translation in simplified Chinese, while maintaining the HTML structure: ```html 前端测试的有效提示工程技巧 ``` In this HTML snippet: - `` is used to wrap the translated text to ensure it stands out from the rest of the content, as it's not clear how the translated text is to be integrated into your existing HTML structure.

为了充分利用ChatGPT进行前端测试,请考虑以下有用的提示和技巧:

示例提示

生成初始测试:

Sure, here's the translation of "Generate unit tests for X, focusing on Y, Z, and S." in simplified Chinese while keeping the HTML structure: ```html 生成针对 X 的单元测试,重点关注 Y、Z 和 S。 ``` This HTML structure ensures that the translated text maintains its integrity and can be seamlessly integrated into a webpage or document.

Certainly! Here's the text translated into simplified Chinese while keeping the HTML structure: ```html 生成针对此React按钮组件的单元测试,重点测试渲染、点击事件和禁用状态。 ``` In this HTML structure, the translated Chinese text is embedded within `

` tags, maintaining the structure specified.

Sure, here's the translated text in simplified Chinese while keeping the HTML structure: ```html

提示 #1:不要直接粘贴大段代码,而是将代码分成更小的可管理部分。这种做法有助于 ChatGPT 更好地理解上下文并生成更精确的测试用例。

```

添加边缘情况:

Sure, here's how you can structure the HTML while including the translated text: ```html

Translate Text to Chinese

Translate Text to Chinese

Expand on these test cases to include scenarios like X, Y and Z.

扩展这些测试用例,包括像 X、Y 和 Z 这样的场景。

``` In the `

` tag where the English text is originally placed, I've added the simplified Chinese translation below it. This maintains the HTML structure while incorporating the translated text as requested.

扩展这些测试用例,以包括处理不同按钮类型和边缘情况(如空标签)的场景。

Sure, here is the translated text in simplified Chinese while keeping the HTML structure: ```html

提示 #2: 清楚地定义你需要的测试要求或场景。你越具体,ChatGPT 就能更好地根据你的确切需求提供建议。

```

检查现有的测试:

Certainly! Here's the translation of the text into simplified Chinese, keeping the HTML structure: ```html

这里是关于X的测试案例。您能否建议任何额外的测试或改进措施?

``` In this HTML snippet, `

` tags are used to encapsulate the translated text, maintaining the structure typical for HTML content.

Certainly! Here's the translated text in simplified Chinese while keeping the HTML structure intact: ```html

这里是我按钮组件的测试用例。你能建议任何额外的测试或改进吗?

```

提示#3:使用ChatGPT生成初始的测试用例,然后根据您的具体要求和边界情况对其进行审查和完善。迭代细化确保测试套件是全面的,并涵盖所有相关的情况。

陷阱和需要注意的事项

虽然ChatGPT是一个强大的工具,但并非没有局限性:

  • Sure, here is the translated text in simplified Chinese while keeping the HTML structure intact: ```html

    复杂组件:对于大型或高度复杂的前端组件,如果提供的代码结构混乱,GPT 生成的测试可能不总是正确的。这是一个很好的练习,尽量简化您的代码,在未来可以避免维护方面的头疼!

    ``` This HTML snippet contains the translated text in simplified Chinese within a paragraph (`

    ` tag).

  • Certainly! Here is the simplified Chinese translation of the text, keeping the HTML structure intact: ```html

    上下文至关重要:确保代码片段配有足够的解释或上下文,以帮助人工智能准确理解需求。人工智能非常聪明,但它目前还不能读心思。

    ``` In this HTML snippet: - `

    ` denotes a paragraph tag. - The Chinese text is enclosed within the paragraph tag, ensuring it's structured correctly within an HTML document.

Certainly! Here's the translation of "AI-generated tests need review too" in simplified Chinese, while keeping the HTML structure intact: ```html AI-generated tests need review too ``` Translated to simplified Chinese: ```html 人工智能生成的测试也需要审查 ```

正如我上面提到的,人工智能还不能读取我们的思维(我想?)。自动化代码生成,特别是用于测试的代码生成,取决于所提供的提示和指导。

一个常见的陷阱是过分依赖AI生成的代码而没有进行彻底审查。例如,ChatGPT可能会生成由于测试断言结构的限制而默认通过的测试。这可能会导致一种虚假的安全感,使您的测试看起来全面但未能捕捉到关键性的错误。

Sure, here's the text "Example pitfall:" translated to simplified Chinese while keeping the HTML structure: ```html 示例陷阱: ``` In this translation: - `` is used to ensure the text is styled as inline content. - "示例陷阱:" is the simplified Chinese translation of "Example pitfall:".

让我们假设ChatGPT为React组件的onClick事件生成一个测试。如果提示过于通用,人工智能可能会忽略重要的边缘案例,比如防止默认操作或处理不同的事件类型。这可能导致测试仅表面检查功能,而没有深入探讨更深入、更复杂的场景。

如何避免这种情况:

  1. Certainly! Here's the translation of the provided text into simplified Chinese, keeping the HTML structure: ```html

    彻底的审查:始终像审查手写的测试一样审查由AI生成的测试。寻找逻辑漏洞、过于简单的断言以及可能被忽略的边缘情况。

    ``` In simplified Chinese: ```html

    彻底的审查:始终像审查手写的测试一样审查由AI生成的测试。寻找逻辑漏洞、过于简单的断言以及可能被忽略的边缘情况。

    ``` This HTML structure preserves the text content while indicating it's a paragraph (`

    ` tag) for web display.

  2. 与文档进行交叉验证:确保您的测试与组件或存储的预期功能一致,并且符合文档要求。如果文档不完整,应格外注意定义每个测试应该达到的目标。
  3. Certainly! Here's the translated text in simplified Chinese while keeping the HTML structure intact: ```html 经常运行测试:定期运行和重复运行测试,及早发现任何意外行为或测试覆盖中的空白。 ``` This HTML structure ensures that the translated text maintains the same formatting as the original English text.

结论 (Conclusion)

Certainly! Here's the translated text in simplified Chinese, keeping the HTML structure intact: ```html

AI 动力前端测试具有显著潜力,可缩短开发时间并增加测试覆盖率。通过使用 ChatGPT 生成单元测试、扩展测试场景,甚至审查现有覆盖范围,开发人员可以专注于更复杂、更创造性的任务。然而,保持警惕非常重要,彻底审查 AI 生成的代码,确保符合必要的标准,并真正增强应用程序的质量。

``` This HTML snippet contains the translated text in simplified Chinese, structured as a paragraph.

AI工具如ChatGPT可以简化您的测试流程,但人类监督仍然至关重要,以确保质量和可靠性。通过保持批判的眼光,积极地改进由AI生成的测试,您可以有效地利用ChatGPT,同时减轻风险。

现在,我要走了,我需要和我的Google Home Mini做一些修改。

2024-08-28 04:14:17 AI中文站翻译自原文