get()을 사용해 쿼리를 실행하고 한개의 객체 결과를 {} 가져온다. 여기서는 id 한개를 가져온다
findTask(id:number) {
const SelectOne = this.db.query("SELECT * FROM tasks WHERE id =?")
return SelectOne.get(id)
}
all()은 쿼리를 실행하고 객체배열로 반환한다 [{},{},{},{},{}] 즉 모든 객체들을 반환!
findTasks() {
const selectMany = this.db.query("SELECT * FROM tasks")
return selectMany.all()
}
나머지 CREATE,UPDATE,DELETE는 run()을 사용하여 쿼리실행한다.
updataTask(id:number, task:Omit<Task,"id">) {
const update = this.db.prepare("UPDATE tasks SET title =? WHERE id=?")
update.run(task.title,id)
}
업데이트 할때 같은 쿼리를 여러 번 실행할 때마다 새로 컴파일하지 않도록 prepare()로 미리 쿼리를 준비해둔다. 이렇게 하면 컴파일 단계를 생략하고 바로 실행할 수 있어 성능이 향상된다!
Omit<Task,"id">은 Task타입에 "id:number", "title:string"이 있는데 id는 자동생성되도록 제외시키고 title만 수정한다.
실행전 insert, 실행후에는 tasks테이블을 삭제한다.
// 실행전
beforeEach(() => {
db.exec("INSERT INTO tasks (title) VALUES ('독서'),('코딩'),('명상'),('게임')");
service = new TaskService(db)
})
// 실행후 tasks테이블을 모두 삭제
afterEach(() => {
db.exec("DELETE FROM tasks")
})
toEqual로 새로만든 객체가 같은지 비교 toHaveLength는 길이비교 기존 4개에서 한개 추가됬으니 5개가 맞다
test("createTask", () => {
service.createTask({title:"산책"})
expect(db.query("SELECT * FROM tasks").all()).toHaveLength(5)
expect(db.query("SELECT * FROM tasks WHERE id = 5").get()).toEqual({
id:5,
title:"산책"
})
})
toHaveProperty()는 객체의 "키", "값" 을 검증한다.
test("updateTask", () => {
expect(db.query("SELECT * FROM tasks WHERE id = 4").get()).toHaveProperty(
"title",
"게임"
)
service.updataTask(4,{title:"게임(삭제예정)"})
expect(db.query("SELECT * FROM tasks WHERE id =4").get()).toHaveProperty(
"title",
"게임(삭제예정)"
)
})
삭제를했으니 toBeNull() null값 검증!
test("deleteTask", () => {
service.deleteTask(5)
expect(db.query("SELECT * FROM tasks").all()).toHaveLength(4)
expect(db.query("SELECT * FROM tasks WHERE id=5").get()).toBeNull()
})
실행결과

참고한 사이트 및 책
Expect · Jest
When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things.
jestjs.io
https://bun.sh/docs/api/sqlite
SQLite – API | Bun Docs
Bun natively implements a high-performance SQLite3 driver. To use it import from the built-in bun:sqlite module. The API is simple, synchronous, and fast. Credit to better-sqlite3 and its contributors for inspiring the API of bun:sqlite. The bun:sqlite mod
bun.sh
https://www.yes24.com/Product/Goods/134021042
헬로 Bun - 예스24
타입스크립트와 JSX를 아우르는 런타임 Bun으로 만나는 차세대 웹 개발 느리고 복잡한 노드 생태계의 판도를 바꾸기 위해, 차세대 자바스크립트 런타임이자 올인원 개발 키트인 Bun이 탄생했다.
www.yes24.com