Skip to content

Commit

Permalink
fix: spanner mock now creates unique client setups per project
Browse files Browse the repository at this point in the history
Wipe can be made by calling spanner.close()
  • Loading branch information
JohanObrink committed Feb 17, 2025
1 parent 54e7797 commit 3a3891d
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
12 changes: 7 additions & 5 deletions packages/spanner-migrate/src/__tests__/apply.spec.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import { type Database, Spanner } from '@google-cloud/spanner'
import type {
ExecuteSqlRequest,
Transaction,
} from '@google-cloud/spanner/build/src/transaction'
import type { ExecuteSqlRequest } from '@google-cloud/spanner/build/src/transaction'
import { applyDown, applyUp } from '../apply'
import type { Migration } from '../types'

describe('apply', () => {
let spanner: jest.Mocked<Spanner>
let db: jest.Mocked<Database>

beforeEach(() => {
// Assume `Database` is mocked globally
db = new Spanner()
spanner = new Spanner() as jest.Mocked<Spanner>
db = spanner
.instance('my-instance')
.database('my-database') as jest.Mocked<Database>
jest.clearAllMocks()
})
afterEach(() => {
spanner.close()
})

describe('applyUp', () => {
it('should apply the up script and record the migration', async () => {
Expand Down
3 changes: 3 additions & 0 deletions packages/spanner-migrate/src/__tests__/db.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ describe('prepare', () => {
instance = spanner.instance('my-instance') as jest.Mocked<Instance>
database = instance.database('my-database') as jest.Mocked<Database>
})
afterEach(() => {
spanner.close()
})
describe('ensure ensureMigrationTable', () => {
it('checks if table exists', async () => {
await ensureMigrationTable(database)
Expand Down
18 changes: 17 additions & 1 deletion packages/spanner-mock/src/spanner.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { jest } from '@jest/globals'
import { createMockInstance } from './instance'

export const createSpanner = () => {
type SpannerArgs = {
projectId?: string
}

const spannerClients = new Map()
const createNewSpannerClient = (projectId: string) => {
const instances = new Map<string, ReturnType<typeof createMockInstance>>()
return {
instance: jest.fn((instanceName: string) => {
Expand All @@ -10,5 +15,16 @@ export const createSpanner = () => {
}
return instances.get(instanceName)
}),
close: jest.fn(() => {
spannerClients.delete(projectId)
}),
}
}

export const createSpanner = (args: SpannerArgs) => {
const projectId = args?.projectId || ''
if (!spannerClients.has(projectId)) {
spannerClients.set(projectId, createNewSpannerClient(projectId))
}
return spannerClients.get(projectId)
}

0 comments on commit 3a3891d

Please sign in to comment.