1. 程式人生 > 其它 >[Unit testing] Improve Error Messages by Generating Test Titles

[Unit testing] Improve Error Messages by Generating Test Titles

One of the most crucial things you can do when writing tests is ensuring that the error message explains the problem as clearly as possible so it can be addressed quickly. Let’s improve our test by generating test titles so error messages are more descriptive.

//auth.js

function isPasswordAllowed(password) {
  
return ( password.length > 6 && // non-alphanumeric /\W/.test(password) && // digit /\d/.test(password) && // capital letter /[A-Z]/.test(password) && // lowercase letter /[a-z]/.test(password) ) }
import {isPasswordAllowed} from '../auth'

describe(
'isPasswordAllowed', () => { const allowedPwds = ['!aBc123'] const disallowedPwds = { 'too short': 'a2c!', 'no alphabet characters': '123456', 'no numbers': 'ABCdef!', 'no uppercase letters': 'abc123!', 'no lowercase letters': 'ABC123!', 'no non-alphanumeric characters': 'ABCdef123', } allowedPwds.forEach((pwd)
=> { test(`allow ${pwd}`, () => { expect(isPasswordAllowed(pwd)).toBeTruthy() }) }) Object.entries(disallowedPwds).forEach(([key, value]) => { test(`disallow - ${key}: ${value}`, () => { expect(isPasswordAllowed(value)).toBeFalsy() }) }) })