Skip to content

Commit

Permalink
test: add tests for makeReactive
Browse files Browse the repository at this point in the history
  • Loading branch information
hlysine committed May 23, 2023
1 parent 3c898f3 commit 7839eaf
Showing 1 changed file with 63 additions and 2 deletions.
65 changes: 63 additions & 2 deletions src/__tests__/component.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import { act, render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { makeReactive, ref } from '..';
import { makeReactive, ref, useWatchEffect } from '..';
import { perf, wait } from 'react-performance-testing';
import 'jest-performance-testing';

Expand All @@ -15,7 +15,7 @@ describe('Reactive component', () => {
const content = await findByText('Test component');
expect(content).toBeTruthy();
});
it('react to ref changes', async () => {
it('re-renders when ref changes', async () => {
const count = ref(0);
const Tester = makeReactive(function Tester() {
return <p>{count.value}</p>;
Expand All @@ -40,4 +40,65 @@ describe('Reactive component', () => {
expect(content).toBeTruthy();
});
});
it('transfers component attributes correctly', () => {
const propTypes = {};
const contextTypes = {};
const defaultProps = {};
const displayName = 'DisplayTester';
function Tester() {
return <p>Test component</p>;
}
Tester.propTypes = propTypes;
Tester.contextTypes = contextTypes;
Tester.defaultProps = defaultProps;
Tester.displayName = displayName;

const converted = makeReactive(Tester);

expect(converted.propTypes).toBe(propTypes);
expect(converted.contextTypes).toBe(contextTypes);
expect(converted.defaultProps).toBe(defaultProps);
expect(converted.displayName).toBe(displayName);
expect(converted.name).toBe(Tester.name);
});
it('stops reactive effects on unmount', async () => {
const mockEffect = jest.fn();
const mockCleanup = jest.fn();
const count = ref(0);
const Tester = makeReactive(function Tester() {
useWatchEffect(() => {
mockEffect(count.value);
return mockCleanup;
});
return <p>{count.value}</p>;
});

const { unmount, findByText } = render(<Tester />);

expect(mockEffect.mock.calls).toHaveLength(1);
expect(mockCleanup.mock.calls).toHaveLength(0);
const content1 = await findByText('0');
expect(content1).toBeTruthy();

act(() => {
count.value++;
});

expect(mockEffect.mock.calls).toHaveLength(2);
expect(mockCleanup.mock.calls).toHaveLength(1);
const content2 = await findByText('1');
expect(content2).toBeTruthy();

unmount();

expect(mockEffect.mock.calls).toHaveLength(2);
expect(mockCleanup.mock.calls).toHaveLength(2);

act(() => {
count.value++;
});

expect(mockEffect.mock.calls).toHaveLength(2);
expect(mockCleanup.mock.calls).toHaveLength(2);
});
});

0 comments on commit 7839eaf

Please sign in to comment.