[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面试题 搞定PHP面试 - 函数知识点整理 php 面试题目整理 PHP面试整理 PHP面试 概述 感觉现在发面试题有些冷门,就跟昨天德国那场 ...
- React碰到v-if
最近在重构公司老项目,由于本人以前的技术栈是vue, 换工作后发现现在公司的技术栈是react, 所以重构的过程是及其痛苦.加之项目又是几年前的老项目,不敢大改,比葫芦画瓢比比皆是.本文就介绍下遇到的 ...
- struct 区别 在C 和C++ 中
C语言中: Struct是用户自定义数据类型(UDT). C++语言中: Struct是抽象数据类型(ADT),支持成员函数的定义. 在C++中,struct的成员的默认访问说 ...
- file结构体
struct file结构体定义在include/linux/fs.h中定义.文件结构体代表一个打开的文件,系统中的每个打开的文件在内核空间都有一个关联的 struct file.它由内核在打开文件时 ...
- 哈夫曼树:HDU5884-Sort(队列、哈夫曼树)
Sort Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) 题目链接:http://ac ...
- arrive 和reach 的区别
例如:He arrived yesterday. 没宾语的话就用arrive了reach作抵达讲时是及物动词,后面要宾语的 分清arrive和reach的区别arrive是不及物动词,后面不能直接加地 ...
- 【转】js里的时间函数集
$(function(){ var mydate = new Date(); var t=mydate.toLocaleString(); $("#time").text(t); ...
- android 之 ListView相关
ListView是一种列表视图,其将ListAdapter所提供的各个控件显示在一个垂直且可滚动的列表中.需要注意的为创建适配器并将其设置给ListView. 1.ArrayAdapter Array ...
- Etree方式解析xml知识积累
movies.xml: <collection shelf="New Arrivals"> <movie title="Enemy Behind&quo ...
- 数组dome
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...