Skip to content

Commit

Permalink
fix: check url match before trigger showSurvey (#1732)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasheriques authored Feb 14, 2025
1 parent 2c364cc commit fb78108
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/__tests__/extensions/surveys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,49 @@ describe('usePopupVisibility URL changes should hide surveys accordingly', () =>
expect(window.history.pushState).toBe(originalPushState)
expect(window.history.replaceState).toBe(originalReplaceState)
})

it('should not show delayed survey if URL no longer matches when delay expires', () => {
jest.useFakeTimers()

// Create a survey with a URL condition and a 2 second delay
const survey = createTestSurvey({
url: '/initial-path',
urlMatchType: 'exact',
})
survey.appearance = { surveyPopupDelaySeconds: 2 }

// Set initial matching URL
Object.defineProperty(window, 'location', {
value: new URL('https://example.com/initial-path'),
writable: true,
})

// Start the survey visibility hook
const { result } = renderHook(() => usePopupVisibility(survey, posthog, 2000, false, mockRemoveSurveyFromFocus))

// Initially the survey should not be visible (due to delay)
expect(result.current.isPopupVisible).toBe(false)

// Change URL to non-matching path before delay expires
act(() => {
Object.defineProperty(window, 'location', {
value: new URL('https://example.com/different-path'),
writable: true,
})
window.dispatchEvent(new Event('popstate'))
})

// Advance timers past the delay
act(() => {
jest.advanceTimersByTime(2000)
})

// Survey should still not be visible since URL no longer matches
expect(result.current.isPopupVisible).toBe(false)
expect(mockRemoveSurveyFromFocus).toHaveBeenCalledWith('test-survey')

jest.useRealTimers()
})
})

describe('preview renders', () => {
Expand Down
6 changes: 6 additions & 0 deletions src/extensions/surveys.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,12 @@ export function usePopupVisibility(
}

const showSurvey = () => {
// check if the url is still matching, necessary for delayed surveys, as the URL may have changed
// since the survey was scheduled to appear
if (!doesSurveyUrlMatch(survey)) {
return
}

setIsPopupVisible(true)
window.dispatchEvent(new Event('PHSurveyShown'))
posthog.capture('survey shown', {
Expand Down

0 comments on commit fb78108

Please sign in to comment.