Repository navigation
Expand file tree
/
Copy pathindex.test.js
More file actions
264 lines (224 loc) · 9.01 KB
/
Copy pathindex.test.js
File metadata and controls
264 lines (224 loc) · 9.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest'
vi.mock('ora', () => {
return {
default: vi.fn(() => ({
start: vi.fn().mockReturnThis(),
succeed: vi.fn().mockReturnThis(),
fail: vi.fn().mockReturnThis(),
clear: vi.fn().mockReturnThis(),
render: vi.fn().mockReturnThis()
}))
}
})
vi.mock('open', () => ({
default: vi.fn()
}))
vi.mock('shelljs', () => ({
default: {
exec: vi.fn().mockImplementation((cmd, options, callback) => {
if (cmd.includes('git remote get-url')) {
return { stdout: 'https://github.com/user/repo.git' }
}
// Handle async exec for git push
if (options && options.async) {
// Create a mock child process that can be killed and emits exit afterwards
let killed = false
const listeners = { exit: [] }
const mockChild = {
stdout: {
on: vi.fn((event, handler) => {
if (event === 'data') {
setTimeout(() => handler(Buffer.from('Everything up-to-date\n')), 10)
}
})
},
stderr: {
on: vi.fn((event, handler) => {
// no stderr by default
})
},
on: vi.fn((event, handler) => {
if (event === 'exit') {
listeners.exit.push(handler)
// Simulate successful exit after a short delay unless killed
setTimeout(() => {
const code = killed ? 1 : 0
listeners.exit.forEach((cb) => cb(code))
}, 20)
}
}),
kill: vi.fn(() => {
killed = true
})
}
return mockChild
}
if (callback) {
callback(0, 'success', '')
}
return { code: 0, stdout: 'success', stderr: '' }
}),
which: vi.fn().mockReturnValue(true)
}
}))
vi.mock('git-branch', () => ({
default: vi.fn().mockResolvedValue('feature-branch')
}))
const originalConsoleLog = console.log
console.log = vi.fn()
import ora from 'ora'
import open from 'open'
import gitPushPR, { getPullRequestUrl } from './index.js'
import shell from 'shelljs'
const { exec, which } = shell
import branch from 'git-branch'
let exitSpy
beforeEach(() => {
vi.clearAllMocks()
exitSpy = vi.spyOn(process, 'exit').mockImplementation((code) => {
throw new Error(`process.exit unexpectedly called with "${code}"`)
})
})
afterEach(() => {
exitSpy.mockRestore()
vi.clearAllMocks()
vi.clearAllTimers()
})
afterAll(() => {
console.log = originalConsoleLog
})
describe('getPullRequestUrl', () => {
it('should generate correct GitHub pull request URL', () => {
const url = getPullRequestUrl('https://github.com/user/repo.git', 'feature-branch', '')
expect(url).toBe('https://github.com/user/repo/pull/new/feature-branch')
})
it('should generate correct BitBucket pull request URL', () => {
const url = getPullRequestUrl('https://bitbucket.org/user/repo.git', 'feature-branch', '')
expect(url).toBe('https://bitbucket.org/user/repo/pull-requests/new?source=feature-branch&t=1')
})
it('should generate correct GitLab merge request URL', () => {
const url = getPullRequestUrl('https://gitlab.com/user/repo.git', 'feature-branch', '')
expect(url).toBe('https://gitlab.com/user/repo/merge_requests/new?merge_request%5Bsource_branch%5D=feature-branch')
})
it('should extract URL from stderr for unknown Git hosts', () => {
const stderr =
'remote: Create a pull request for feature-branch on GitHub by visiting:\nremote: https://example.com/user/repo/pull/new/feature-branch\n'
const url = getPullRequestUrl('https://example.com/user/repo.git', 'feature-branch', stderr)
expect(url).toBe('https://example.com/user/repo/pull/new/feature-branch')
})
})
describe('gitPushPR', () => {
it('should not exit if current branch is protected but allowAll is true', async () => {
const protectedBranches = ['main', 'master', 'develop']
for (const branchName of protectedBranches) {
branch.mockResolvedValueOnce(branchName)
const promise = gitPushPR({ allowAll: true, remote: 'origin' })
await new Promise((resolve) => setTimeout(resolve, 50))
expect(exitSpy).not.toHaveBeenCalled()
await promise
}
})
it('should use force flag when option is set', async () => {
const promise = gitPushPR({ force: true, remote: 'origin' })
await new Promise((resolve) => setTimeout(resolve, 50))
expect(exec).toHaveBeenCalledWith(expect.stringContaining('--force'), expect.any(Object))
await promise
})
it('should use no-verify flag when verify option is false', async () => {
const promise = gitPushPR({ verify: false, remote: 'origin' })
await new Promise((resolve) => setTimeout(resolve, 50))
expect(exec).toHaveBeenCalledWith(expect.stringContaining('--no-verify'), expect.any(Object))
await promise
})
it('should use silent flag when option is set', async () => {
const promise = gitPushPR({ silent: true, remote: 'origin' })
await new Promise((resolve) => setTimeout(resolve, 50))
expect(exec).toHaveBeenCalledWith(expect.stringContaining('--quiet'), expect.any(Object))
expect(ora).not.toHaveBeenCalled()
await promise
})
it('should use custom remote when specified', async () => {
const promise = gitPushPR({ remote: 'upstream' })
await new Promise((resolve) => setTimeout(resolve, 50))
expect(exec).toHaveBeenCalledWith(expect.stringContaining('upstream'), expect.any(Object))
await promise
})
it('should open a pull request URL after successful push', async () => {
const promise = gitPushPR({ remote: 'origin' })
await new Promise((resolve) => setTimeout(resolve, 50))
expect(open).toHaveBeenCalled()
await promise
})
it('should gracefully abort on SIGINT (Ctrl+C)', async () => {
// Start the process
const promise = gitPushPR({ remote: 'origin' })
// Emit SIGINT shortly after to simulate Ctrl+C
setTimeout(() => process.emit('SIGINT'), 5)
// Wait to allow the mocked child to exit and our handler to run
await new Promise((resolve) => setTimeout(resolve, 200))
// Since we no longer call process.exit on abort, just assert no PR was opened and spinner failed path was taken
expect(open).not.toHaveBeenCalled()
await promise
})
const expectExitWithError = async (fn) => {
let error
try {
await fn()
} catch (e) {
error = e
}
expect(error).toBeInstanceOf(Error)
expect(error.message).toBe('process.exit unexpectedly called with "1"')
}
it('should exit if Git is not installed', async () => {
which.mockReturnValueOnce(false)
await expectExitWithError(() => gitPushPR({ remote: 'origin' }))
})
it('should exit if branch name cannot be retrieved', async () => {
branch.mockRejectedValueOnce(new Error('Failed to get branch'))
await expectExitWithError(() => gitPushPR({ remote: 'origin' }))
})
it('should exit if current branch is protected and allowAll is false', async () => {
const protectedBranches = ['main', 'master', 'develop']
for (const branchName of protectedBranches) {
branch.mockResolvedValueOnce(branchName)
await expectExitWithError(() => gitPushPR({ allowAll: false, remote: 'origin' }))
}
})
it('should stream stdout/stderr and show two separate spinners', async () => {
const mockSpinner1 = {
start: vi.fn().mockReturnThis(),
succeed: vi.fn().mockReturnThis(),
fail: vi.fn().mockReturnThis(),
clear: vi.fn().mockReturnThis(),
render: vi.fn().mockReturnThis()
}
const mockSpinner2 = {
start: vi.fn().mockReturnThis(),
succeed: vi.fn().mockReturnThis(),
fail: vi.fn().mockReturnThis(),
clear: vi.fn().mockReturnThis(),
render: vi.fn().mockReturnThis()
}
// First call returns spinner1, second call returns spinner2
ora.mockReturnValueOnce(mockSpinner1).mockReturnValueOnce(mockSpinner2)
// Execute the command
const promise = gitPushPR({ remote: 'origin' })
// Wait a bit for async operations to complete
await new Promise((resolve) => setTimeout(resolve, 50))
// Verify first spinner (git push) clear/render was called for streaming output
expect(mockSpinner1.clear).toHaveBeenCalled()
expect(mockSpinner1.render).toHaveBeenCalled()
// Verify first spinner succeeded with push message
expect(mockSpinner1.succeed).toHaveBeenCalledWith(expect.stringContaining('[git-push-pr]: pushed code to remote'))
expect(mockSpinner1.succeed).toHaveBeenCalledTimes(1)
// Verify second spinner (PR creation) succeeded with PR URL
expect(mockSpinner2.succeed).toHaveBeenCalledWith(expect.stringContaining('[git-push-pr]: pull request ready at:'))
expect(mockSpinner2.succeed).toHaveBeenCalledTimes(1)
// Verify two ora instances were created
expect(ora).toHaveBeenCalledTimes(2)
expect(ora).toHaveBeenNthCalledWith(1, '[git-push-pr]: pushing code to remote\n')
expect(ora).toHaveBeenNthCalledWith(2, '[git-push-pr]: creating pull request\n')
await promise
})
})