[Unit Testing] Fundamentals of Testing in Javascript
In this lesson, we’ll get the most fundamental understanding of what an automated test is in JavaScript. A test is code that throws an error when the actual result of something does not match the expected output.
Tests can get more complicated when you’re dealing with code that depends on some state to be set up first (like a component needs to be rendered to the document before you can fire browser events, or there needs to be users in the database). However, it is relatively easy to test pure functions (functions which will always return the same output for a given input and not change the state of the world around them).
Base file to test against:
math.js
const sum = (a, b) => a - b;
const subtract = (a, b) => a - b; const sumAsync = (...args) => Promise.resolve(sum(...args));
const subtractAsync = (...args) => Promise.resolve(subtract(...args)); module.exports = { sum, subtract, sumAsync, subtractAsync };
index.js
const { sum, subtract } = require("./math"); let result, expected; result = sum(, );
expected = ;
if (actual !== expected) {
throw new Error(`${result} is not equal to ${expected}`);
} result = subtract(, );
expected = ;
if (actual !== expected) {
throw new Error(`${result} is not equal to ${expected}`);
}
Let’s add a simple layer of abstraction in our simple test to make writing tests easier. The assertion library will help our test assertions read more like a phrase you might say which will help people understand our intentions better. It will also help us avoid unnecessary duplication.
const { sum, subtract } = require("./math"); let result, expected; result = sum(, );
expected = ;
expect(result).toBe(expected); result = subtract(, );
expected = ;
expect(result).toBe(expected); function expect(actual) {
return {
toBe(expected) {
if (actual !== expected) {
throw new Error(`${actual} is not equal to ${expected}`);
}
}
};
}
This is also a common way to write a assetion library, expect() function take a actual value and return an object contains 'toBe', 'toEqual'... functions.
One of the limitations of the way that this test is written is that as soon as one of these assertions experiences an error, the other tests are not run. It can really help developers identify what the problem is if they can see the results of all of the tests.
Let’s create our own test
function to allow us to encapsulate our automated tests, isolate them from other tests in the file, and ensure we run all the tests in the file with more helpful error messages.
const { sum, subtract } = require("./math"); let result, expected; test("sum adds numbers", () => {
result = sum(, );
expected = ;
expect(result).toBe(expected);
}); test("subtract substracts numbers", () => {
result = subtract(, );
expected = ;
expect(result).toBe(expected);
}); function test(title, cb) {
try {
cb();
console.log(`%c ✔︎ ${title}`, "color: green");
} catch (err) {
console.error(`✘ ${title}`);
console.error(err);
}
}
Our testing framework works great for our synchronous test. What if we had some asynchronous functions that we wanted to test? We could make our callback functions async
, and then use the await
keyword to wait for that to resolve, then we can make our assertion on the result
and the expected
.
Let’s make our testing framework support promises so users can use async/await.
const { sumAsync, subtractAsync } = require("./math"); let result, expected; test("sum adds numbers", async () => {
result = await sumAsync(3, 7);
expected = 10;
expect(result).toBe(expected);
}); test("subtract substracts numbers", async () => {
result = await subtractAsync(7, 3);
expected = 4;
expect(result).toBe(expected);
}); function test(title, cb) {
try {
cb();
console.log(`%c ✔︎ ${title}`, "color: green");
} catch (err) {
console.error(`✘ ${title}`);
console.error(err);
}
} function expect(actual) {
return {
toBe(expected) {
if (actual !== expected) {
throw new Error(`${actual} is not equal to ${expected}`);
}
}
};
}
To fix the problem, we can make our testing lib async / await.
async function test(title, cb) {
try {
await cb();
console.log(`%c ✔︎ ${title}`, "color: green");
} catch (err) {
console.error(`✘ ${title}`);
console.error(err);
}
}
Not it works normal again.
These testing utilities that we built are pretty useful. We want to be able to use them throughout our application in every single one of our test files.
Some testing frameworks provide their helpers as global variables. Let’s implement this functionality to make it easier to use our testing framework and assertion library. We can do this by exposing our test
and expect
functions on the global object available throughout the application.
setup-global.js:
async function test(title, cb) {
try {
await cb();
console.log(`%c ✔︎ ${title}`, "color: green");
} catch (err) {
console.error(`✘ ${title}`);
console.error(err);
}
} function expect(actual) {
return {
toBe(expected) {
if (actual !== expected) {
throw new Error(`${actual} is not equal to ${expected}`);
}
}
};
} global.test = test;
global.expect = expect;
Run:
node --require ./setup-global.js src/index.js
Up to this point we’ve created all our own utilities. As it turns out, the utilities we’ve created mirror the utilities provided by Jest perfectly! Let’s install Jest and use it to run our test!
npx jest
[Unit Testing] Fundamentals of Testing in Javascript的更多相关文章
- 【Android Api 翻译1】Android Texting(2)Testing Fundamentals 测试基础篇
Testing Fundamentals The Android testing framework, an integral part of the development environment, ...
- Android Texting(2)Testing Fundamentals 测试基础篇
Testing Fundamentals The Android testing framework, an integral part of the development environment, ...
- Unit Testing, Integration Testing and Functional Testing
转载自:https://codeutopia.net/blog/2015/04/11/what-are-unit-testing-integration-testing-and-functional- ...
- Android测试:Fundamentals of Testing
原文地址:https://developer.android.com/training/testing/fundamentals.html 用户在不同的级别上与你的应用产生交互.从按下按钮到将信息下载 ...
- Difference Between Performance Testing, Load Testing and Stress Testing
http://www.softwaretestinghelp.com/what-is-performance-testing-load-testing-stress-testing/ Differen ...
- Go testing 库 testing.T 和 testing.B 简介
testing.T 判定失败接口 Fail 失败继续 FailNow 失败终止 打印信息接口 Log 数据流 (cout 类似) Logf format (printf 类似) SkipNow 跳过当 ...
- [Testing] Config jest to test Javascript Application -- Part 1
Transpile Modules with Babel in Jest Tests Jest automatically loads and applies our babel configurat ...
- [Testing] Config jest to test Javascript Application -- Part 3
Run Jest Watch Mode by default locally with is-ci-cli In CI, we don’t want to start the tests in wat ...
- [Testing] Config jest to test Javascript Application -- Part 2
Setup an afterEach Test Hook for all tests with Jest setupTestFrameworkScriptFile With our current t ...
随机推荐
- 【php】运算符优先级界定
<?php $i = 1; $array[$i] = $i++; print_r($array);die; //输出 Array([2] => 1) $a = 1; echo $a + $ ...
- 【php】 给数组重建索引
array_values $a = [1,2]; unset($a[1]); $a[] = 3; print_r($a); // 输出 [0=>1,2=>3]
- Python9-模块2-序列化-day20
序列化 什么叫序列化——将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化. 序列就是字符串 序列化的目的1.以某种存储形式使自定义对象持久化:2.将对象从一个地方传递到另一个地方.3.使程序 ...
- NSArray 排序
先研究一种方法 NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:]; ; i < ; i++) { ; [arr ...
- Android开发工具——Gradle知识汇总
1.什么是构建工具 Eclipse大家都知道是一种IDE(集成开发环境),最初是用来做Java开发的,而Android是基于Java语言的,所以最初Google还是希望Android能在Eclipse ...
- django的rest framework框架——分页、视图、路由、渲染器
一.rest framework的分页 1.使用rest framework内置类PageNumberPagination实现分类 from django.conf.urls import url f ...
- AWK原理及命令和文件输入
一.awk简介 1.awk是3个姓氏的首字母,代表该语言的3个作者,awk的版本有很多,包括:旧版awk,新版awk(nawk),GNU awk(gawk)等. awk程序有awk命令,括在引 ...
- ssh执行远程服务器脚本 提示php: command not found
ssh执行远程服务器脚本 提示php: command not found 设置环境变量 一台机器作为管理机,来管理其他服务器,并通过key认证,免密码登陆的. 在管理机上通过ssh登陆到其他服务器来 ...
- x86实模式到保护模式 李忠 王晓波
x86实模式到保护模式 李忠 王晓波 第3到4章 各个进制间的转换省略 实验环境 编译器 nasm 虚拟机 virtual box 小程序 hexview 观察编译后的机器代码 fixvhd ...
- nginx,lvs,haproxy负载均衡对比
Nginx/LVS/HAProxy是目前使用最广泛的三种负载均衡软件,一般对负载均衡的使用是随着网站规模的提升根据不同的阶段来使用不同的技术,具体的应用需求还得具体分析. 如果是中小型的Web应用,比 ...