似乎我编写的测试在表创建之前被调用。 实际上,在测试中调用的计数是在创建表之前完成的,然后服务器启动并重新进行测试。
我以前没有看到这种行为,我搜索了几个小时,但没有找到任何可能导致这种情况的原因。
setup.ts
beforeAll(async () => {
const connectionManager = getConnectionManager()
const connection = connectionManager.create({
type: 'postgres',
host: 'localhost',
port: 54320,
username: 'test',
password: 'test',
database: 'bitsky_test',
entities: ['../src/entities/*.ts'],
logging: true,
synchronize: true,
})
await connection.connect()
})
afterAll(async () => {
await getConnection().dropDatabase()
await getConnection().close()
})
app.ts
const version: string = '0.0.1'
const mode: string = 'Development'
const port: number = 5030
export const startApp = () => {
dotenv.config()
const router: Application = express()
applyMiddleware(commonMiddlewares, router)
router.use('/auth', authRouter())
return router
}
createConnection().then(() => {
startApp().listen(port, () => {
ServerLogger.log(serverGreetings, logLevels.MISC)
ServerLogger.log(`Version: ${version} ${mode} mode\n`, logLevels.MISC)
ServerLogger.log(`Server running on port ${port}!`)
})
})
测试调用的方法
const repository: Repository<User> = getRepository(User)
// Check unique email
const emailTaken: number = await repository.count({ where: { email: data.email }})
if (emailTaken) {
return Boom.badRequest('email_already_taken')
}
// Hashing password
const saltRounds: number = parseInt(`${process.env.SALT_ROUNDS}`, 10)
const clearPassword: string = data.password
data.password = await bcrypt.hash(clearPassword, saltRounds)
// Saving user
const user: User = repository.create(data)
await repository.save(user)
// Generating token & deleting password
return authenticate(data.email, clearPassword)
测试 const app = startApp()
describe('POST /auth/create', () => {
it('Create a user', async () => {
const user: IStringTMap<string> = {
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@bitsky.be',
password: 'iliketrains!',
}
const res: Response = await request(app)
.post('/auth/create')
.send(user)
.expect(200)
expect(res.body.email).toBe('john.doe@bitsky.be')
expect(res.body.password).toBe(undefined)
})
})