[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 ...
随机推荐
- 使用 HTML5 Geolocation 构建基于地理位置的 Web 应用学习网站分享
HTML5 中的新功能 HTML5 是最新一代的 HTML 规范,是 W3C 与 WHATWG 合作的结果,目前仍外于开发中.自从上一代 HTML4,Web 世界已经发生了巨大的变化,HTML5 的到 ...
- 2019年6月14日 Web框架之Django_07 进阶操作(MTV与MVC、多对多表三种创建方式、前后端传输数据编码格式contentType、ajax、自定义分页器)
摘要 MTV与MVC 多对多表三种创建方式 ajax ,前后端传输数据编码格式contentType 批量插入数据和自定义分页器 一.MVC与MTV MVC(Model View Controller ...
- day22面向对象
面向对象编程: 1.什么是面向对象 面向过程(编程思想): 过程,解决问题的步骤,流程即第一步做什么,第二步做什么 将复杂问题,拆成若干小问题,按照步骤一一解决,将复杂问题流程化(为其制定固定的实现流 ...
- One-to-one
创建模型 在本例中,Place 和 Restaurant 为一对一关系 from django.db import models class Place(models.Model): name = m ...
- Python编程快速上手--实践项目11.11.1
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time def messa ...
- 合肥工业大学数据结构上机实验代码与实验报告(全)github地址
我已经将这个学期的所有数据结构上机实验的代码与报告上传到github上了,一直都有这个想法,但没抽出时间来学习git.经过上周简单的练习后,我已经基本学会运营自己的代码仓库了.所有代码都是C++写的类 ...
- MySQL 2003 [ERROR] /usr/sbin/mysqld: Incorrect key file for table './keyword_search/keyword.MYI'; try to repair it
今天对一个有四百多万数据的表增加一个功能时,当做数据插入时,显示没有插入,到Linux的log下面查看了发现下面这条错误信息 在stacOver上面找到这句: 存储引擎(MyISAM)支持修复表.你应 ...
- 使用镜像源安装EASY_INSTALL和PIP教程
使用easy_install和pip可以让python的模块的安装和管理变得非常方便.我一般在新的Linux系统上,先easy_install pip然后就用pip安装其他的模块了. 不过,在国内用官 ...
- Java 线程池的原理与实现学习(二)
java类库中提供的线程池简介: java提供的线程池更加强大,相信理解线程池的工作原理,看类库中的线程池就不会感到陌生了. execute(Runnable command):履行Ruannable ...
- 【极角排序+双指针线性扫】2017多校训练七 HDU 6127 Hard challenge
acm.hdu.edu.cn/showproblem.php?pid=6127 [题意] 给定平面直角坐标系中的n个点,这n个点每个点都有一个点权 这n个点两两可以连乘一条线段,定义每条线段的权值为线 ...