Skip to content

Commit

Permalink
feat(taro): 新增 useAutoStopPullDownRefresh
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 10, 2020
1 parent 52f8ef8 commit 4338980
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/taro/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@

// @index(['./**/*.ts', '!./**/*.test.*'], f => `export * from '${f.path}'`)
export * from './submit'
export * from './useAutoStopPullDownRefresh'
// @endindex
44 changes: 44 additions & 0 deletions src/taro/useAutoStopPullDownRefresh.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import * as Taro from '@tarojs/taro'
import { renderHook } from '@testing-library/react-hooks'
import { wait } from '../utils'

describe('useAutoStopPullDownRefresh', () => {
let callback: () => any
const usePullDownRefresh: any = jest.fn().mockImplementation(cb => {
callback = cb
})
const stopPullDownRefresh: any = jest.fn()

beforeAll(() => {
jest.mock(
'@tarojs/taro',
() =>
({
usePullDownRefresh,
stopPullDownRefresh,
} as typeof Taro),
)
})

test('表现正常', async () => {
const { useAutoStopPullDownRefresh } = await import(
'./useAutoStopPullDownRefresh'
)
const cb = jest.fn()
renderHook(() => useAutoStopPullDownRefresh(cb))
expect(usePullDownRefresh).toBeCalled().toBeCalledTimes(1)
expect(stopPullDownRefresh).not.toBeCalled()
expect(callback).toBeFunction()
callback()
expect(stopPullDownRefresh).toBeCalled().toBeCalledTimes(1)
expect(cb).toBeCalled().toBeCalledTimes(1)

const cbAsync = jest.fn().mockImplementation(async () => wait(10))
renderHook(() => useAutoStopPullDownRefresh(cbAsync))
callback()
expect(cbAsync).toBeCalled().toBeCalledTimes(1)
expect(stopPullDownRefresh).toBeCalled().toBeCalledTimes(1)
await wait(11)
expect(stopPullDownRefresh).toBeCalled().toBeCalledTimes(2)
})
})
18 changes: 18 additions & 0 deletions src/taro/useAutoStopPullDownRefresh.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { isPromiseLike } from '../utils'
import { stopPullDownRefresh, usePullDownRefresh } from '@tarojs/taro'

/**
* 同 `Taro.usePullDownRefresh`,不过在回调函数完成后会自动调用 `Taro.stopPullDownRefresh()`。
*
* @param callback 回调函数
*/
export function useAutoStopPullDownRefresh(callback: () => any) {
usePullDownRefresh(() => {
const res = callback()
if (isPromiseLike(res)) {
res.then(() => stopPullDownRefresh())
} else {
stopPullDownRefresh()
}
})
}

0 comments on commit 4338980

Please sign in to comment.