Guide / Sample for Testing with Jest
See original GitHub issueIt would be great to have a guide to using jest and typeorm together.
This guide would ideally have patterns for both using real connections for integration testing as well as mocking the TypeORM connection / repository / etc entirely.
Currently, if we mock jest.mock
TypeORM the entity definitions stop working as expected.
Original Issue Description Below
Issue type:
[ X ] question [ ] bug report [ X ] feature request [ ] documentation issue
Database system/driver:
[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql
/ mariadb
[ ] oracle
[ X] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo
TypeORM version:
[ X] latest
[ ] @next
[ ] 0.x.x
(or put your version here)
Is there any standard way to test typeorm based model etc.? I don’t mind direct connection to database for integration testing (especially mocking gets too complex)
I setup global connection like this.
export async function setupConn(drop=false) {
conn = await createConnection({
type: "postgres",
synchronize: drop,
dropSchema: drop,
logging: false,
url: "postgres://quantum@localhost/test",
entities: [__dirname + "/../../src/entities/**/*.js"],
})
return conn
}
Then I tried to use global setup/ different environment calling setupConn function but the problem is:
Jest spawns worker for each test suites (different *.test.js) file.
So I always see this error
{"data": null, "errors": [[GraphQLError: Connection "default" was not found.]]}
but if i use same function at beforeAll at test suites it works for 1 test suite .
So is there any good and recommend way to test application developed using typeorm.
And thanks for making such a beautiful orm I really enjoy using it 😃
Issue Analytics
- State:
- Created 4 years ago
- Reactions:25
- Comments:28 (3 by maintainers)
Top GitHub Comments
Solution for unit test with TypeORM (edited with @sarfata recommendations, thanks!)
it’s working now, hope it helps you guys and please let me know if there is any improvement.
settings
package.json
ormconfig.ts
src/libraries/loadEnv.ts
jest.config.js
src/test-utils/db-env.ts
server.ts
Test
src/entities/Postgres/User/tests/User.test.ts
Docker (optional - for development only, never use docker for db)
docker-compose.db.yaml
@guiaramos I believe with your solution each test file will redrop and recreate the database completely. This might take a bit of time.
Instead, you can define a
globalSetup
to run the migrations and connect (without executing migrations) in each of your tests.This works for me and took me a very long time to figure out. I 👍 this issue, there should be clearer documentation on how to do this.
jest.config
setup-db.ts
db-env.ts
And my
createDatabaseConnection
is just: