惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News | PayPal Newsroom
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
S
Security @ Cisco Blogs
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
Help Net Security
Help Net Security
Latest news
Latest news
NISL@THU
NISL@THU
S
Security Affairs
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
小众软件
小众软件
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
AWS News Blog
AWS News Blog
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
I
InfoQ
Schneier on Security
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
IT之家
IT之家
T
Threatpost
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
S
SegmentFault 最新的问题

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Triangulation in Test-Driven Development
Dmitri Pavlutin · 2022-10-04 · via Dmitri Pavlutin Blog

Test-driven development (aka TDD) consists of 3 phases: the red, the green, and the refactor.

The transition from green to refactor phase involves the generalization of the code under test. Especially if you've been using the faking technique in the green phase.

The idea of triangulation is to use 2 assertions to drive a safer creation of the generic code.

Let's see in more detail how triangulation works.

Note: if you're not familiar with test-driven development, I recommend checking TDD in JavaScript video guide before continuing with the article.

1. Example: develop a sum calculator

A good way to understand the benefits of the triangulation technique is to follow an example.

Let's say that you'd like to create a simple function: calculate the sum of 2 numbers. And let's imagine that you're unsure whether the addition operator is the right way to implement the sum.

Step 1: red

When doing TDD, I always start with the simplest test possible. In this case, I'm going to import the sum function and check that it returns undefined.

First, you need to write the unit test of the sum function:


import { sum } from './sum'

describe('sum()', () => {

it('should execute', () => {

expect(sum()).toBeUndefined()

})

})


Of course, the test throws an error because the module sum.js doesn't exist.


FAIL sum.spec.js

● Test suite failed to run

Cannot find module './sum' from 'sum.test.js'


Step 2: green

Let's then create the sum.js module exporting a simple function with an empty body:

The unit test passes and I'm successfully in the green phase.


PASS sum.spec.js

sum()

✓ should execute (1 ms)


Step 3: red

Now let's continue with the proper addition testing. Let's update the unit test to verify whether the function returns correctly the sum of 2 numbers: 1 and 2.


import { sum } from './sum'

describe('sum()', () => {

it('should calculate sum', () => {

expect(sum(1, 2)).toBe(3)

})

})


Running the updated test triggers an assertion error because currently the sum() implementation does nothing.


FAIL sum.spec.js

sum()

✕ should calculate sum (3 ms)

● sum() › should calculate sum

expect(received).toBe(expected) // Object.is equality

Expected: 3

Received: undefined

3 | describe('sum()', () => {

4 | it('should calculate sum', () => {

> 5 | expect(sum(1, 2)).toBe(3)

| ^

6 | })

7 | })

8 |


Step 4: green

Because the green phase has to be passed as soon as possible (with any programming sins you can imagine), let's use a fake implementation and simply return 3.


export function sum() {

return 3

}


Now the fake function passes the unit test.


PASS sum.spec.js

sum()

✓ should calculate sum (2 ms)


Step 5: red

In the previous 4 steps, I followed the standard TDD. Nothing fancy.

Now starts the interesting part.

Instead of going to the refactor phase to write the sum implementation, and because I'm unsure that 1 assertion is enough to test my future generic code, let's get back to the red phase and write another assertion:


import { sum } from './sum'

describe('sum()', () => {

it('should calculate sum', () => {

expect(sum(1, 2)).toBe(3)

expect(sum(3, 4)).toBe(7)

})

})


This is the triangulation technique in practice: you use 2 assertions to drive the generalization of the code.

Running the test fails because of the second assertion.


FAIL sum.spec.js

sum()

✕ should calculate sum (4 ms)

● sum() › should calculate sum

expect(received).toBe(expected) // Object.is equality

Expected: 7

Received: 3

4 | it('should calculate sum', () => {

5 | expect(sum(1, 2)).toBe(3)

> 6 | expect(sum(3, 4)).toBe(7)

| ^

7 | })

8 | })

9 |


Step 6: green

Having the 2 assertions that check the future code, let's write the proper implementation of the sum:


export function sum(n1, n2) {

return n1 + n2

}


The unit test successfully passes. The addition code has been generated from the 2 assertions and now I have more confidence in the correctness of my generic solution.


PASS sum.spec.js

sum()

✓ should calculate sum (2 ms)


Step 7: refactor

Now the generic code is created and the assertions prove it working. You can remove one of the assertions:


import { sum } from './sum'

describe('sum()', () => {

it('should calculate sum', () => {

expect(sum(1, 2)).toBe(3)

})

})


Of course, running the unit test still passes.


PASS sum.spec.js

sum()

✓ should calculate sum (2 ms)


2. Triangulation

Having seen the triangulation in practice, let's formulate a simple definition of it.

Triangulation is a technique that involves writing 2 assertions to drive a safer creation of a more general implementation.

In the previous example, triangulation has been used in step 5 to force the creation of a more general solution in step 6.

Triangulation in Test-Driven Development

Now you might be asking yourself: why exactly 2 assertions are necessary and why a single assertion is not enough?

3. Example: things going wrong

Let's say I take an alternative approach at step 5. Without using the triangulation technique I go directly to refactor phase and throw a flawed generic solution.

Step 5: refactor (alternative)

Let's try the following generic solution:


export function sum(n) {

return n + 2

}


What I've done is just dump a simple but flawed generic solution. What's interesting, is that the unit test, the one defined in step 3 with 1 assertion... still passes!


import { sum } from './sum'

describe('sum()', () => {

it('should calculate sum', () => {

expect(sum(1, 2)).toBe(3)

})

})



PASS sum.spec.js

sum()

✓ should calculate sum (2 ms)


But having used the triangulation technique here, the flawed generic solution wouldn't have passed the unit test with 2 assertions:


import { sum } from './sum'

describe('sum()', () => {

it('should calculate sum', () => {

expect(sum(1, 2)).toBe(3)

expect(sum(3, 4)).toBe(7)

})

})



FAIL sum.spec.js

sum()

✕ should calculate sum (4 ms)

● sum() › should calculate sum

expect(received).toBe(expected) // Object.is equality

Expected: 7

Received: 5

4 | it('should calculate sum', () => {

5 | expect(sum(1, 2)).toBe(3)

> 6 | expect(sum(3, 4)).toBe(7)

| ^

7 | })

8 | })

9 |


4. Conclusion

I like the triangulation technique because it helps to create a generic implementation by reducing misses along the way.

You will find the technique useful when you're not sure about the correctness of the generic code you want to write. Having 2 assertions can give you more confidence.

In what scenarios do you find the triangulation technique useful?