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的更多相关文章

  1. 【Android Api 翻译1】Android Texting(2)Testing Fundamentals 测试基础篇

    Testing Fundamentals The Android testing framework, an integral part of the development environment, ...

  2. Android Texting(2)Testing Fundamentals 测试基础篇

    Testing Fundamentals The Android testing framework, an integral part of the development environment, ...

  3. Unit Testing, Integration Testing and Functional Testing

    转载自:https://codeutopia.net/blog/2015/04/11/what-are-unit-testing-integration-testing-and-functional- ...

  4. Android测试:Fundamentals of Testing

    原文地址:https://developer.android.com/training/testing/fundamentals.html 用户在不同的级别上与你的应用产生交互.从按下按钮到将信息下载 ...

  5. Difference Between Performance Testing, Load Testing and Stress Testing

    http://www.softwaretestinghelp.com/what-is-performance-testing-load-testing-stress-testing/ Differen ...

  6. Go testing 库 testing.T 和 testing.B 简介

    testing.T 判定失败接口 Fail 失败继续 FailNow 失败终止 打印信息接口 Log 数据流 (cout 类似) Logf format (printf 类似) SkipNow 跳过当 ...

  7. [Testing] Config jest to test Javascript Application -- Part 1

    Transpile Modules with Babel in Jest Tests Jest automatically loads and applies our babel configurat ...

  8. [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 ...

  9. [Testing] Config jest to test Javascript Application -- Part 2

    Setup an afterEach Test Hook for all tests with Jest setupTestFrameworkScriptFile With our current t ...

随机推荐

  1. perl学习之FLOCK函数的调用(讲的非常好)

    一段演示flock系统调用的perl程序http://www.extmail.org/forum/viewthread.php?tid=1066

  2. linux下ls出现文件的后缀有@,* ,/之类的解释

    ls -Fafptool*  img_maker*    lzcmp@     lzfgrep@   lzma*         lzmore*         node-pre-gyp@bower@ ...

  3. linux中test的意义 又可以表示为[]

    测试标志 代表意义 文件名.文件类型 -e 该文件名是否存在 -f 该文件名是否存在且为file -d 该文件名是否存在且为目录 -b 该文件名是否存在且为一个block -c 该文件名是否存在且为一 ...

  4. LeetCode(92) Reverse Linked List II

    题目 Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1- ...

  5. H.264 Profile-level-id

    基于SIP协议的VOIP通信,该字段通常位于视频协商sdp报文中,如: video RTP/AVP rtpmap: H264/ fmtp: profile-level-id=42801E; packe ...

  6. Linux下配置MySQL主从复制

    一.环境准备 本次准备两台Linux主机,操作系统都为CentOS6.8, 都安装了相同版本的MySQL.(MySQL5.7). 主从服务器的防火墙都开启了3306端口. 相关信息如下: [主服务器] ...

  7. [android 开发篇] 易白教程网址

    http://www.yiibai.com/android/android_bluetooth.html

  8. 九度oj 题目1020:最小长方形

    题目描述:     给定一系列2维平面点的坐标(x, y),其中x和y均为整数,要求用一个最小的长方形框将所有点框在内.长方形框的边分别平行于x和y坐标轴,点落在边上也算是被框在内. 输入: 测试输入 ...

  9. BZOJ4199 [Noi2015]品酒大会 【后缀数组 + 单调栈 + ST表】

    题目 一年一度的"幻影阁夏日品酒大会"隆重开幕了.大会包含品尝和趣味挑战两个环节,分别向优胜者颁发"首席品 酒家"和"首席猎手"两个奖项,吸 ...

  10. 能量项链(codevs 1154)

    题目描述 Description 在Mars星球上,每个Mars人都随身佩带着一串能量项链.在项链上有N颗能量珠.能量珠是一颗有头标记与尾标记的珠子,这些标记对应着某个正整数.并且,对于相邻的两颗珠子 ...