Skip to main content

Command Palette

Search for a command to run...

使用pg进行postgre数据库写入的测试

Published
•1 min read•View as Markdown
import { afterAll, describe, it, expect } from 'vitest'
import { Pool } from 'pg'

import { db } from './your-db'

describe('createUser', () => {
  const pool = new Pool()
  afterAll(async () => {
    await pool.query('DROP TABLE IF EXISTS users')
    await pool.end()
  })
  it('inserts a user to database', async () => {
    const userDraft = {
      email: 'example@gmail.com',
      verificationCode: '123456'
    }    
    const createdUser = await db.createUser(userDraft)
    const user = await pool.query('SELECT * FROM user WHERE id = $1', [createdUser.id])
    expect(user.email).toBe(userDraft.email)
  })
})

使用Pool的end方法,因为直接使用pool的query方法时,会从池里取一个client执行SQL,并且在执行结束后自动释放该client。

如果是使用pool的connect方法,则会取出一个client,需要手动使用该client去query,且需要手动调用release方法讲该client放回池里。

More from this blog

Untitled Publication

11 posts