Skip to content

Commit

Permalink
Fix the timezone test and a missing minus in the timezone fallback (#986
Browse files Browse the repository at this point in the history
)
  • Loading branch information
Finesse committed Jan 31, 2024
1 parent 872bb49 commit fb161e6
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
51 changes: 49 additions & 2 deletions src/sources/timezone.test.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,65 @@
import { withMockProperties } from '../../tests/utils'
import getTimezone from './timezone'

describe('Sources', () => {
describe('timezone', () => {
it('returns a tz identifier in all supported browsers', () => {
const result = getTimezone()

// Some devices on BrowserStack return 'UTC'.
if (result === 'UTC') {
// Some devices on BrowserStack return 'UTC', some '+00:00'.
if (result === 'UTC' || /^[+-]\d{2}:\d{2}$/.test(String(result))) {
return
}

// We expect all modern browsers (with default settings) to return a TZ identifier,
// like 'Europe/Berlin' or 'America/Argentina/Buenos_Aires'.
expect(result).toMatch(/^([a-z]\/+)?[a-z]+\/[a-z_]+$/gi)
})

describe('fallbacks', () => {
function withNoTimezone(januaryOffset: number, julyOffset: number, action: () => void) {
class MockDate {
args: unknown[]

constructor(...args: unknown[]) {
this.args = args
}

getFullYear() {
return 2024
}

getTimezoneOffset() {
if (this.args[1] === 0) {
return januaryOffset
}
if (this.args[1] === 6) {
return julyOffset
}
throw TypeError('Unexpected constructor arguments')
}
}

return withMockProperties(window, { Date: { value: MockDate }, Intl: undefined }, action)
}

it('in the northern eastern hemisphere (Berlin)', async () => {
await withNoTimezone(1 * -60, 2 * -60, () => {
expect(getTimezone()).toEqual('UTC+60')
})
})

it('in the southern western hemisphere (Santiago)', async () => {
await withNoTimezone(-3 * -60, -4 * -60, () => {
expect(getTimezone()).toEqual('UTC-240')
})
})

it('in the middle', async () => {
await withNoTimezone(0, 0, () => {
expect(getTimezone()).toEqual('UTC+0')
})
})
})
})
})
2 changes: 1 addition & 1 deletion src/sources/timezone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default function getTimezone(): string {
// For browsers that don't support timezone names
// The minus is intentional because the JS offset is opposite to the real offset
const offset = -getTimezoneOffset()
return `UTC${offset >= 0 ? '+' : ''}${Math.abs(offset)}`
return `UTC${offset >= 0 ? '+' : ''}${offset}`
}

function getTimezoneOffset(): number {
Expand Down

0 comments on commit fb161e6

Please sign in to comment.