Node.js의 assert 모듈은 함수 검증(assertion)을 위한 다양한 기능을 제공합니다. 그중 assert.ok() 함수는 전달된 값이 참(truthy)인지 여부를 테스트하며, 값이 참이 아닐 경우 AssertionError를 발생시킵니다.
문법
assert.ok(value, [message])
매개변수 설명
value – 참인지 검사할 값으로, 이 값이 falsy(거짓으로 평가되는 값)이면 에러가 발생합니다.
message – 선택적 매개변수로, 에러 발생 시 출력할 사용자 정의 메시지를 지정할 수 있습니다.
assert 모듈 설치하기
npm install assert
assert 모듈은 Node.js에 내장된 모듈이므로 별도 설치 없이 바로 사용할 수 있습니다. 최신 버전을 확인하려면 아래 명령어를 실행하세요.
npm version assert
모듈 불러오기
const assert = require("assert").strict;예제 1: 조건이 참일 경우
먼저 assertOk.js라는 이름의 파일을 생성하고 아래 코드를 작성한 뒤, 다음 명령어로 실행해 보세요.
node assertOk.js
assertOK.js
// 모듈 불러오기
const assert = require('assert').strict;
try {
// 값의 타입 검사
assert.ok(typeof 21 === 'number');
console.log("NO ERROR!")
} catch(error) {
console.log("Error: ", error)
}실행 결과
C:\home\node>> node assertOk.js NO ERROR!
typeof 21 === 'number'는 true로 평가되므로 에러 없이 정상적으로 실행됩니다.
예제 2: 조건이 거짓일 경우
이번에는 조건이 false가 되도록 코드를 변경해 보겠습니다.
// 모듈 불러오기
const assert = require('assert').strict;
try {
// 값의 타입 검사
assert.ok(typeof 21 === 'string');
console.log("NO ERROR!")
} catch(error) {
console.log("Error: ", error)
}실행 결과
C:\home\node>> node assertOk.js
Error: { AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy
value:
assert.ok(typeof 21 === 'string')
at Object. (/home/node/test/assert.js:6:9)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
generatedMessage: true,
name: 'AssertionError [ERR_ASSERTION]',
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '==' }typeof 21 === 'string'은 false로 평가되기 때문에 AssertionError가 발생하고, catch 블록에서 해당 에러 정보를 출력합니다.
정리
assert.ok()는 간단하지만 강력한 검증 도구입니다. 주로 테스트 코드에서 특정 조건이 반드시 참이어야 하는 경우에 활용되며, 조건이 충족되지 않으면 프로그램 실행을 중단하고 개발자에게 문제를 알려줍니다.