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. modprode

    modprobe命令 1.modprobe 命令是根据depmod -a的输出/lib/modules/version/modules.dep来加载全部的所需要模块. 2.删除模块的命令是:modpr ...

  2. Python多版本共存安装

    Python的安装 进入Python官方网站:www.python.org下载系统对应的Python版本 按照提示步奏安装,安装路径选择自定义,方便查找 安装完成后,按win+R键,输入cmd进入cm ...

  3. int long long 的范围

    unsigned   int     0-4294967295   (10位数,4e9) int                        -2147483648-2147483647  (10位 ...

  4. 快速入门Matplotlib

    十分钟快速入门Matplotlib 函数式绘图 这个库主要有两种绘图方式,一种是像这样的类matlab的函数式绘图方法. import matplotlib.pyplot as plt import ...

  5. Luogu3195 [HNOI2008]玩具装箱TOY (方程变形 + 斜率优化 )

    题意: 给出一个序列 {a[i]} 把其分成若干个区间,每个区间的价值为 W = (j − i + ∑ak(i<=k<=j) - L)​2 ,求所有分割方案中价值之和的最小值. 细节: 仔 ...

  6. Tomcat下部署PHP

    php线程安全版和非线程安全版本区别 1.windows + IIS + FastCGI :使用非线程安全版本. 解释: 以FastCGI方式安装PHP时,PHP拥有独立的进程,并且FastCGI是单 ...

  7. 7,数据类型转换,set 集合,和深浅copy

    str转换成list  用split list转换成str  用join tuple转换成list tu1 = (1,2,3) li = list(tu1)(强转) tu2 = tuple(li)(强 ...

  8. java第五章 子类与继承

    5.1子类与父类 1   java不支持多重继承,即一个子类不可以从多个父类中同时继承,而C++中可以. 人们习惯地称子类与父类的关系式“is—a”的关系 2   再类的声明过程中,通过关键字exte ...

  9. c++ stack,queue,vector基本操作

    stack 的基本操作有:入栈,如例:s.push(x);出栈,如例:s.pop();注意,出栈操作只是删除栈顶元素,并不返回该元素.访问栈顶,如例:s.top()判断栈空,如例:s.empty(), ...

  10. 【loj6029】「雅礼集训 2017 Day1」市场

    题目 题意:四种操作,区间加法.区间除法(下取整).区间求最小值.区间求和. 第1.3.4个操作都是摆设,关键在于如何做区间除法. 很明显不能直接把区间的和做除法后向下取整,因为区间和可能会多凑出一个 ...