Middle
How to speed up tests by reusing context?
sobes.tech AI
Answer from AI
To speed up tests, you can reuse the context (for example, application, database, or environment context) instead of creating it anew for each test. This is especially useful for integration tests where initialization can be time-consuming.
Approaches:
- Use setup/teardown at the level of the entire test suite (for example, in
TestMainin Go orbeforeAll/afterAllin Jest) to create the context once. - Cache connections to the database, external services, or mocks.
- Use a shared context with a timeout within tests, which is passed to functions.
Example in Go using TestMain:
var testCtx context.Context
func TestMain(m *testing.M) {
testCtx = context.Background()
// Initialize shared resources
setupDatabase()
code := m.Run()
// Clean up resources
teardownDatabase()
os.Exit(code)
}
func TestSomething(t *testing.T) {
// Use testCtx instead of creating a new one
result := DoSomething(testCtx)
if result != expected {
t.Errorf("unexpected result")
}
}
This approach reduces overhead for environment setup and speeds up test execution.