Skip to content

Commit

Permalink
Merge pull request alibaba#1659 from miracles1919/master
Browse files Browse the repository at this point in the history
test(useDrag): add some tests
  • Loading branch information
crazylxr authored Jun 12, 2022
2 parents b7472b5 + 1cb57ec commit 39fff7f
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
7 changes: 7 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,11 @@ module.exports = {
tsconfig: 'tsconfig.json',
},
},
collectCoverageFrom: [
'<rootDir>/**/src/**/*.{js,jsx,ts,tsx}',
'!**/demo/**',
'!**/example/**',
'!**/es/**',
'!**/lib/**',
],
};
62 changes: 62 additions & 0 deletions packages/hooks/src/useDrag/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { renderHook } from '@testing-library/react-hooks';
import useDrag, { Options } from '../index';
import type { BasicTarget } from '../../utils/domTarget';

const setup = <T>(data: T, target: BasicTarget, options?: Options) =>
renderHook(() => useDrag(data, target, options));

const events = {};
const mockTarget = {
addEventListener: jest.fn((event, callback) => {
events[event] = callback;
}),
removeEventListener: jest.fn((event) => {
Reflect.deleteProperty(events, event);
}),
setAttribute: jest.fn(),
};

describe('useDrag', () => {
it('should be defined', () => {
expect(useDrag).toBeDefined();
});

it('should add/remove listener on mount/unmount', () => {
const { unmount } = setup(1, mockTarget as any);
expect(mockTarget.addEventListener).toBeCalled();
expect(mockTarget.addEventListener.mock.calls[0][0]).toBe('dragstart');
expect(mockTarget.addEventListener.mock.calls[1][0]).toBe('dragend');
expect(mockTarget.setAttribute).toBeCalledWith('draggable', 'true');
unmount();
expect(mockTarget.removeEventListener).toBeCalled();
});

it('should triggle drag callback', () => {
const onDragStart = jest.fn();
const onDragEnd = jest.fn();
const mockEvent = {
dataTransfer: {
setData: jest.fn(),
},
};
setup(1, mockTarget as any, {
onDragStart,
onDragEnd,
});
events['dragstart'](mockEvent);
expect(onDragStart).toBeCalled();
expect(mockEvent.dataTransfer.setData).toBeCalledWith('custom', '1');
events['dragend'](mockEvent);
expect(onDragEnd).toBeCalled();
});

it(`should not work when target don't support addEventListener method`, () => {
Object.defineProperty(mockTarget, 'addEventListener', {
get() {
return false;
},
});
setup(1, mockTarget as any);
expect(mockTarget.setAttribute).not.toBeCalled();
});
});

0 comments on commit 39fff7f

Please sign in to comment.