javascript 测试是软件开发的一个重要方面,可确保代码的可靠性和健壮性。作为一名开发人员,我发现实施全面的测试策略不仅可以尽早发现错误,还可以提高应用程序的整体质量。让我们探索五种基本的 javascript 测试技术,这些技术在我的经验中被证明是非常宝贵的。
单元测试构成了任何可靠测试策略的基础。它涉及单独测试各个函数、方法和组件,以验证它们的行为是否符合预期。我经常使用 jest(一种流行的 javascript 测试框架)来编写和运行单元测试。以下是使用 jest 进行简单单元测试的示例:
1
2
3
4
5
6
7
8
9
function add(a, b) {
return a + b;
}
test(add function correctly adds two numbers, () => {
expect(add(2, 3)).tobe(5);
expect(add(-1, 1)).tobe(0);
expect(add(0, 0)).tobe(0);
});
在此示例中,我们正在测试基本的加法函数,以确保它为各种输入生成正确的结果。像这样的单元测试可以帮助我们捕获各个功能中的错误,并使重构代码变得更容易、更有信心。
除了单个单元之外,集成测试还检查应用程序的不同部分如何协同工作。该技术验证组件是否正确交互以及数据在它们之间正确流动。例如,我们可能会测试用户身份验证模块如何与数据库访问层集成。以下是使用 jest 和模拟数据库进行集成测试的示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const userauth = require(./userauth);
const mockdatabase = require(./mockdatabase);
jest.mock(./database, () => mockdatabase);
describe(user authentication, () => {
test(successfully authenticates a valid user, async () => {
const userauth = new userauth();
const result = await userauth.authenticate(validuser, correctpassword);
expect(result).tobe(true);
});
test(fails to authenticate an invalid user, async () => {
const userauth = new userauth();
const result = await userauth.authenticate(invaliduser, wrongpassword);
expect(result).tobe(false);
});
});
在此集成测试中,我们正在验证 userauth 模块是否正确与数据库交互以对用户进行身份验证。通过使用模拟数据库,我们可以控制测试环境并专注于这些组件之间的集成。
端到端(e2e)测试通过模拟真实用户与我们的应用程序的交互,采用整体方法。这项技术可以帮助我们发现只有在系统所有部分协同工作时才可能出现的问题。为此,我经常使用 cypress,一个强大的端到端测试框架。以下是登录表单的 cypress 测试示例:
1
2
3
4
5
6
7
8
9
10
describe(login form, () => {
it(successfully logs in a user, () => {
cy.visit(/login);
cy.get(input[name="username"]).type(testuser);
cy.get(input[name="password"]).type(testpassword);
cy.get(button[type="submit"]).click();
cy.url().should(include, /dashboard);
cy.contains(welcome, test user).should(be.visible);
});
});
此 e2e 测试自动执行导航到登录页面、输入凭据、提交表单以及验证用户是否已成功登录并重定向到仪表板的过程。从用户的角度来看,此类测试对于确保我们的应用程序正常运行非常宝贵。
立即学习“Java免费学习笔记(深入)”;
模拟和存根是我经常用来隔离正在测试的代码并控制外部依赖项的行为的技术。这种方法在处理 api、数据库或其他复杂系统时特别有用。以下是使用 jest 模拟 api 调用的示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const axios = require(axios);
jest.mock(axios);
const fetchuserdata = async (userid) => {
const response = await axios.get(`https://api.example.com/users/${userid}`);
return response.data;
};
test(fetchuserdata retrieves user information, async () => {
const mockuser = { id: 1, name: john doe, email: john@example.com };
axios.get.mockresolvedvalue({ data: mockuser });
const userdata = await fetchuserdata(1);
expect(userdata).toequal(mockuser);
expect(axios.get).tohavebeencalledwith(https://api.example.com/users/1);
});
在此示例中,我们模拟 axios 库以返回预定义的用户对象,而不是进行实际的 api 调用。这使我们能够单独测试 fetchuserdata 函数,而不依赖于外部 api 的可用性或状态。
代码覆盖率是一个指标,可以帮助我们了解测试执行了多少代码库。虽然 100% 覆盖率并不能保证代码没有错误,但它是可能需要额外测试的区域的有用指标。我使用 istanbul(一种与 jest 集成良好的代码覆盖率工具)来生成覆盖率报告。以下是如何配置 jest 以使用 istanbul:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// jest.config.js
module.exports = {
collectcoverage: true,
coveragedirectory: coverage,
coveragereporters: [text, lcov],
coveragethreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
},
};
实施这些测试技术显着提高了我的 javascript 应用程序的质量和可靠性。然而,重要的是要记住测试是一个持续的过程。随着我们的代码库的发展,我们的测试也应该发展。定期审查和更新我们的测试套件可确保其在捕获错误和回归方面保持有效。
我发现特别有用的一个实践是测试驱动开发(tdd)。使用 tdd,我们在实现实际功能之前编写测试。这种方法有助于澄清需求,指导我们的代码设计,并确保每一项功能都有相应的测试。以下是我如何使用 tdd 实现简单计算器功能的示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// calculator.test.js
const calculator = require(./calculator);
describe(calculator, () => {
let calculator;
beforeeach(() => {
calculator = new calculator();
});
test(adds two numbers correctly, () => {
expect(calculator.add(2, 3)).tobe(5);
});
test(subtracts two numbers correctly, () => {
expect(calculator.subtract(5, 3)).tobe(2);
});
test(multiplies two numbers correctly, () => {
expect(calculator.multiply(2, 3)).tobe(6);
});
test(divides two numbers correctly, () => {
expect(calculator.divide(6, 2)).tobe(3);
});
test(throws an error when dividing by zero, () => {
expect(() => calculator.divide(5, 0)).tothrow(cannot divide by zero);
});
});
// calculator.js
class calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
multiply(a, b) {
return a * b;
}
divide(a, b) {
if (b === 0) {
throw new error(cannot divide by zero);
}
return a / b;
}
}
module.exports = calculator;
在这个 tdd 示例中,我们首先为每个计算器操作编写测试,包括被零除等边缘情况。然后,我们实现 calculator 类以使这些测试通过。这种方法确保我们的代码满足指定的要求,并从一开始就具有全面的测试覆盖率。
javascript 测试的另一个重要方面是处理异步代码。 javascript 中的许多操作(例如 api 调用或数据库查询)都是异步的。 jest 提供了多种有效测试异步代码的方法。这是测试异步函数的示例:
1
2
3
4
5
6
7
8
9
10
const fetchdata = require(./api);
test(fetchdata returns correct user data, async () => {
const userdata = await fetchdata(user/123);
expect(userdata).toequal({
id: 123,
name: john doe,
email: john@example.com
});
});
在此测试中,我们使用 async 函数和await 关键字来处理异步 fetchdata 操作。 jest 在完成测试之前会自动等待 promise 解决。
随着我们的应用程序变得越来越复杂,我们经常需要测试具有内部状态或依赖于外部上下文的组件。对于 react 应用程序,我使用 react 测试库,它鼓励以类似于用户与其交互的方式测试组件。这是测试简单计数器组件的示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import react from react;
import { render, fireevent } from @testing-library/react;
import counter from ./counter;
test(counter increments and decrements when buttons are clicked, () => {
const { getbytext, getbytestid } = render(<counter />);
const incrementbtn = getbytext(increment);
const decrementbtn = getbytext(decrement);
const count = getbytestid(count);
expect(count.textcontent).tobe(0);
fireevent.click(incrementbtn);
expect(count.textcontent).tobe(1);
fireevent.click(incrementbtn);
expect(count.textcontent).tobe(2);
fireevent.click(decrementbtn);
expect(count.textcontent).tobe(1);
});
此测试渲染 counter 组件,通过单击按钮模拟用户交互,并验证显示的计数是否正确更改。
性能测试是确保 javascript 应用程序顺利运行的另一个重要方面。虽然由于执行时间可能较长,将性能测试包含在常规测试套件中并不总是可行,但我们可以创建单独的性能测试套件。下面是一个使用 benchmark.js 库来比较不同数组排序算法性能的示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const benchmark = require(benchmark);
const suite = new benchmark.suite;
// test functions
function bubblesort(arr) {
// implementation of bubble sort
}
function quicksort(arr) {
// implementation of quick sort
}
// add tests
suite.add(bubble sort, function() {
const arr = [5, 3, 8, 4, 2];
bubblesort(arr);
})
.add(quick sort, function() {
const arr = [5, 3, 8, 4, 2];
quicksort(arr);
})
// run tests and log results
.on(cycle, function(event) {
console.log(string(event.target));
})
.on(complete, function() {
console.log(fastest is + this.filter(fastest).map(name));
})
.run({ async: true });
此性能测试比较了冒泡排序和快速排序算法的执行速度,帮助我们就在应用程序中使用哪种算法做出明智的决定。
当我们开发更复杂的应用程序时,我们经常需要测试代码在各种条件或不同输入下的行为。基于属性的测试是一种为我们的测试生成随机输入的技术,帮助我们发现边缘情况和意外行为。 fast-check 是 javascript 中基于属性的测试的流行库。这是一个例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const fc = require(fast-check);
const abs = (n) => n < 0 ? -n : n;
test(absolute value is always non-negative, () => {
fc.assert(
fc.property(fc.integer(), (n) => {
expect(abs(n)).tobegreaterthanorequal(0);
})
);
});
test(absolute value of a number is either the number itself or its negation, () => {
fc.assert(
fc.property(fc.integer(), (n) => {
expect(abs(n)).tobe(n) || expect(abs(n)).tobe(-n);
})
);
});
在这些测试中,快速检查会生成随机整数并验证我们的 abs 函数对于所有输入的行为是否正确。
随着我们的测试套件的增长,保持其组织性和可维护性非常重要。我发现有用的一项技术是使用描述块对相关测试进行分组,并使用 beforeeach 和 aftereach 挂钩来设置和拆除测试环境。这种方法可以保持我们的测试干净并减少重复。这是一个例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
describe(User Management, () => {
let userManager;
beforeEach(() => {
userManager = new UserManager();
});
describe(user creation, () => {
test(creates a new user successfully, () => {
const user = userManager.createUser(John, john@example.com);
expect(user.name).toBe(John);
expect(user.email).toBe(john@example.com);
});
test(throws an error for invalid email, () => {
expect(() => userManager.createUser(John, invalid-email)).toThrow(Invalid email);
});
});
describe(user deletion, () => {
test(deletes an existing user, () => {
const user = userManager.createUser(Jane, jane@example.com);
expect(userManager.deleteUser(user.id)).toBe(true);
});
test(returns false when deleting non-existent user, () => {
expect(userManager.deleteUser(non-existent-id)).toBe(false);
});
});
afterEach(() => {
userManager.clear();
});
});
随着应用程序的增长,这种结构化方法使我们的测试更具可读性并且更易于维护。
总之,实施这些 javascript 测试技术显着提高了我代码的质量和可靠性。从验证单个功能的单元测试到模拟用户交互的端到端测试,每种技术在创建强大的应用程序中都发挥着至关重要的作用。通过结合模拟、代码覆盖率分析和基于属性的测试等先进技术,我们可以在各种问题到达生产之前发现它们。请记住,有效的测试是一个持续的过程,随着我们的代码库的发展而发展。通过持续应用这些技术并根据需要调整我们的测试策略,我们可以构建更可靠、可维护和高质量的 javascript 应用程序。
我们的创作
一定要看看我们的创作:
投资者中心 | 智能生活 | 时代与回声 | 令人费解的谜团 | 印度教 | 精英开发 | js学校
我们在媒体上
科技考拉洞察 | 时代与回响世界 | 投资者中央媒体 | 令人费解的谜团 | 科学与时代媒介 | 现代印度教
以上就是健壮代码的基本 JavaScript 测试技术的详细内容,更多请关注php中文网其它相关文章!