Skip to content

Commit

Permalink
test: improve test coverage (#2364)
Browse files Browse the repository at this point in the history
* test(useTimeAgo):useTimeAgo ut statements 100% branches 93.75% functions 100% lines 100%

* test(useChangeCase):useChangeCase ut statements 100% branches 100% functions 100% lines 100%

* test(useStorage):useStorage ut statements 100% branches 100% functions 100% lines 100%

* test(compatibility):compatibility ut statements 100% branches 100% functions 100% lines 100%

* test(useAxios):useAxios ut statements 100% branches 100% functions 100% lines 100%
  • Loading branch information
sun0day committed Nov 9, 2022
1 parent 862d127 commit 65b7bef
Show file tree
Hide file tree
Showing 5 changed files with 322 additions and 102 deletions.
93 changes: 87 additions & 6 deletions packages/core/useStorage/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { debounceFilter, promiseTimeout } from '@vueuse/shared'
import { isVue3, ref } from 'vue-demi'
import { nextTwoTick, useSetup } from '../../.test'
import { useStorage } from '.'
import { StorageSerializers, useStorage } from '.'

const KEY = 'custom-key'

vi.mock('../ssr-handlers', () => ({
getSSRHandler: vi.fn().mockImplementationOnce((_, cb) => () => cb()).mockImplementationOnce(() => () => {
throw new Error('getDefaultStorage error')
}),
}))

describe('useStorage', () => {
const storageState = new Map<string, string | undefined>()
console.error = vi.fn()
const storageState = new Map<string, string | number | undefined>()
const storageMock = {
getItem: vi.fn(x => storageState.get(x)),
setItem: vi.fn((x, v) => storageState.set(x, v)),
Expand All @@ -16,12 +23,18 @@ describe('useStorage', () => {
const storage = storageMock as any as Storage

beforeEach(() => {
localStorage.clear()
storageState.clear()
storageMock.setItem.mockClear()
storageMock.getItem.mockClear()
storageMock.removeItem.mockClear()
})

it('export module', () => {
expect(useStorage).toBeDefined()
expect(StorageSerializers).toBeDefined()
})

it('string', async () => {
const vm = useSetup(() => {
const ref = useStorage(KEY, 'a', storage)
Expand Down Expand Up @@ -64,8 +77,6 @@ describe('useStorage', () => {
})

it('boolean', async () => {
storage.removeItem(KEY)

const store = useStorage(KEY, true, storage)

expect(store.value).toBe(true)
Expand Down Expand Up @@ -169,8 +180,6 @@ describe('useStorage', () => {
})

it('map', async () => {
expect(storage.getItem(KEY)).toEqual(undefined)

const store = useStorage(KEY, new Map<number, string | number>([
[1, 'a'],
[2, 2],
Expand Down Expand Up @@ -358,4 +367,76 @@ describe('useStorage', () => {
const customRef2 = useStorage(KEY, 2, storage, { mergeDefaults: (value, initial) => value + initial })
expect(customRef2.value).toEqual(3)
})

it('use storage value if present', async () => {
storageState.set(KEY, 'true')
expect(useStorage(KEY, false, storage).value).toBe(true)

storageState.set(KEY, '0')
expect(useStorage(KEY, 1, storage).value).toBe(0)

storageState.set(KEY, 0)
expect(useStorage(KEY, 1, storage).value).toBe(0)

storageState.set(KEY, JSON.stringify({}))
expect(useStorage(KEY, { a: 1 }, storage).value).toEqual({})

storageState.set(KEY, '')
expect(useStorage(KEY, null, storage).value).toBe('')

storageState.set(KEY, 'a')
expect(useStorage(KEY, 'b', storage).value).toBe('a')

storageState.set(KEY, JSON.stringify([]))
expect(useStorage(KEY, new Map([[1, 2]]), storage).value).toEqual(new Map([]))

storageState.set(KEY, JSON.stringify([]))
expect(useStorage(KEY, new Set([1, 2]), storage).value).toEqual(new Set([]))
})

it('support shallow ref', async () => {
const data = useStorage(KEY, 0, storage, { shallow: true })
expect(data.value).toBe(0)

data.value = 1
await nextTwoTick()
expect(data.value).toBe(1)
expect(storage.getItem(KEY)).toBe('1')
})

it('watch storage event', async () => {
const data = useStorage(KEY, 0, localStorage)
expect(data.value).toBe(0)

window.dispatchEvent(new StorageEvent('storage'))
await nextTwoTick()
expect(data.value).toBe(0)

data.value = 1
await nextTwoTick()
expect(data.value).toBe(1)

window.dispatchEvent(new StorageEvent('storage', { storageArea: localStorage }))
await nextTwoTick()
expect(data.value).toBe(0)

window.dispatchEvent(new StorageEvent('storage', { storageArea: localStorage, key: 'unknown', newValue: '1' }))
await nextTwoTick()
expect(data.value).toBe(0)

window.dispatchEvent(new StorageEvent('storage', { storageArea: localStorage, key: KEY, newValue: '1' }))
await nextTwoTick()
expect(data.value).toBe(1)
})

it('handle error', () => {
expect(useStorage(KEY, 0).value).toBe(0)
expect(console.error).toHaveBeenCalledWith(new Error('getDefaultStorage error'))

expect(useStorage(KEY, 0, {
getItem: () => null,
setItem: () => { throw new Error('write item error') },
} as any).value).toBeUndefined()
expect(console.error).toHaveBeenCalledWith(new Error('write item error'))
})
})
109 changes: 76 additions & 33 deletions packages/core/useTimeAgo/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { timestamp } from '@vueuse/shared'
import { promiseTimeout, timestamp } from '@vueuse/shared'
import type { ComputedRef } from 'vue-demi'
import { computed, ref } from 'vue-demi'
import { useTimeAgo } from '.'
Expand All @@ -15,6 +15,8 @@ const UNITS = [
{ max: Infinity, value: 31536000000, name: 'year' },
]

const fullDateFormatter = (value: any) => new Date(value).toISOString().slice(0, 10)

function getNeededTimeChange(type: TimeUnit, count: number, adjustSecond?: number) {
const unit = UNITS.find(i => i.name === type)
return (unit?.value || 0) * count + (adjustSecond || 0) * 1000
Expand All @@ -25,44 +27,85 @@ describe('useTimeAgo', () => {
const changeValue = ref(0)
let changeTime: ComputedRef<number>

beforeEach(() => {
function reset() {
vi.useFakeTimers()
baseTime = timestamp()
vi.setSystemTime(baseTime)
changeValue.value = 0
changeTime = computed(() => baseTime + changeValue.value)
}

beforeEach(() => {
reset()
})

afterEach(() => {
vi.useRealTimers()
})

describe('just now', () => {
test('just now', () => {
expect(useTimeAgo(baseTime).value).toBe('just now')
})
test('control now', async () => {
vi.useRealTimers()
const { resume, pause, timeAgo } = useTimeAgo(baseTime, { controls: true, showSecond: true, updateInterval: 500 })
expect(timeAgo.value).toBe('0 second ago')

pause()
await promiseTimeout(1000)
expect(timeAgo.value).toBe('0 second ago')

resume()
await promiseTimeout(1000)
expect(timeAgo.value).toBe('2 seconds ago')
})

describe('second', () => {
test('future: less than 1 minute', () => {
changeValue.value = getNeededTimeChange('minute', 1, -1)
expect(useTimeAgo(changeTime).value).toBe('just now')
})
test('get undefined when time is invalid', () => {
expect(useTimeAgo('invalid date').value).toBeUndefined()
})

test('future: less than 1 minute/ with showSecond', () => {
changeValue.value = getNeededTimeChange('minute', 1, -1)
expect(useTimeAgo(changeTime, { showSecond: true }).value).toBe('in 59 seconds')
describe('just now', () => {
test('just now', () => {
expect(useTimeAgo(baseTime).value).toBe('just now')
})

test('past: less than 1 minute', () => {
changeValue.value = -getNeededTimeChange('minute', 1, -1)
expect(useTimeAgo(changeTime).value).toBe('just now')
test('just now using custom formatter', () => {
// @ts-expect-error mock messages
expect(useTimeAgo(baseTime, { messages: { second: '{0}', future: '{0}' }, showSecond: true }).value).toBe('0')
})
})

test('past: less than 1 minute/ with showSecond', () => {
changeValue.value = -getNeededTimeChange('minute', 1, -1)
expect(useTimeAgo(changeTime, { showSecond: true }).value).toBe('59 seconds ago')
})
describe('second', () => {
function testSecond(isFuture: boolean) {
const text = isFuture ? 'future' : 'past'
const nextTime = getNeededTimeChange('minute', 1, -1) * (isFuture ? 1 : -1)
test(`${text}: less than 1 minute`, () => {
changeValue.value = nextTime
expect(useTimeAgo(changeTime).value).toBe('just now')
})

test(`${text}: less than 1 second`, () => {
changeValue.value = getNeededTimeChange('minute', 1, -59.6) * (isFuture ? 1 : -1)
expect(useTimeAgo(changeTime, { showSecond: true }).value).toBe(
isFuture ? 'in 0 second' : '0 second ago')
})

test(`${text}: less than 1 minute/ with showSecond`, () => {
changeValue.value = nextTime
expect(useTimeAgo(changeTime, { showSecond: true }).value).toBe(
isFuture ? 'in 59 seconds' : '59 seconds ago')
})

test(`${text}: less than 1 minute but more than 10 seconds with showSecond`, () => {
changeValue.value = nextTime
expect(useTimeAgo(changeTime, { showSecond: true, max: 10000 }).value).toBe(fullDateFormatter(changeTime.value))
})

test(`${text}: more than 1 minute`, () => {
changeValue.value = getNeededTimeChange('minute', 1, 1) * (isFuture ? 1 : -1)
expect(useTimeAgo(changeTime, { showSecond: true, max: 'second' }).value).toBe(fullDateFormatter(changeTime.value))
})
}

testSecond(true)
testSecond(false)
})

describe('minute', () => {
Expand All @@ -71,7 +114,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('in 1 minute')
})

test('past: 1 minute', () => {
test('past: 1 minute', () => {
changeValue.value = -getNeededTimeChange('minute', 1)
expect(useTimeAgo(changeTime).value).toBe('1 minute ago')
})
Expand All @@ -81,7 +124,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('in 10 minutes')
})

test('past: 10 minutes', () => {
test('past: 10 minutes', () => {
changeValue.value = -getNeededTimeChange('minute', 10)
expect(useTimeAgo(changeTime).value).toBe('10 minutes ago')
})
Expand All @@ -93,7 +136,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('in 1 hour')
})

test('past: 1 hour', () => {
test('past: 1 hour', () => {
changeValue.value = -getNeededTimeChange('hour', 1)
expect(useTimeAgo(changeTime).value).toBe('1 hour ago')
})
Expand All @@ -103,7 +146,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('in 10 hours')
})

test('past: 10 hours', () => {
test('past: 10 hours', () => {
changeValue.value = -getNeededTimeChange('hour', 10)
expect(useTimeAgo(changeTime).value).toBe('10 hours ago')
})
Expand All @@ -115,7 +158,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('tomorrow')
})

test('past: 1 day', () => {
test('past: 1 day', () => {
changeValue.value = -getNeededTimeChange('day', 1)
expect(useTimeAgo(changeTime).value).toBe('yesterday')
})
Expand All @@ -125,7 +168,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('in 3 days')
})

test('past: 3 days', () => {
test('past: 3 days', () => {
changeValue.value = -getNeededTimeChange('day', 3)
expect(useTimeAgo(changeTime).value).toBe('3 days ago')
})
Expand All @@ -137,7 +180,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('next week')
})

test('past: 1 week', () => {
test('past: 1 week', () => {
changeValue.value = -getNeededTimeChange('week', 1)
expect(useTimeAgo(changeTime).value).toBe('last week')
})
Expand All @@ -147,7 +190,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('in 3 weeks')
})

test('past: 3 weeks', () => {
test('past: 3 weeks', () => {
changeValue.value = -getNeededTimeChange('week', 3)
expect(useTimeAgo(changeTime).value).toBe('3 weeks ago')
})
Expand All @@ -159,7 +202,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('next month')
})

test('past: 1 month', () => {
test('past: 1 month', () => {
changeValue.value = -getNeededTimeChange('month', 1)
expect(useTimeAgo(changeTime).value).toBe('last month')
})
Expand All @@ -169,7 +212,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('in 3 months')
})

test('past: 3 months', () => {
test('past: 3 months', () => {
changeValue.value = -getNeededTimeChange('month', 3)
expect(useTimeAgo(changeTime).value).toBe('3 months ago')
})
Expand All @@ -181,7 +224,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('next year')
})

test('past: 1 year', () => {
test('past: 1 year', () => {
changeValue.value = -getNeededTimeChange('year', 1)
expect(useTimeAgo(changeTime).value).toBe('last year')
})
Expand All @@ -191,7 +234,7 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime).value).toBe('in 3 years')
})

test('past: 3 years', () => {
test('past: 3 years', () => {
changeValue.value = -getNeededTimeChange('year', 3)
expect(useTimeAgo(changeTime).value).toBe('3 years ago')
})
Expand Down
Loading

0 comments on commit 65b7bef

Please sign in to comment.