From b6bebd39b5e79e23de3a57ff7685a317f557b629 Mon Sep 17 00:00:00 2001 From: Mark Lundin Date: Thu, 8 May 2025 15:50:58 +0100 Subject: [PATCH] Add unit tests for Script component and refactor useScript hook - Introduced comprehensive unit tests for the Script component, validating prop passing, ref forwarding, initialization, re-rendering behavior, and cleanup on unmount. - Refactored the useScript hook to support ref forwarding, enhancing the integration with the Script component. - Updated type definitions to improve type safety and clarity in the codebase. These changes enhance the testing coverage and improve the overall functionality of the Script component and its associated hooks. --- packages/lib/src/components/Script.test.tsx | 171 ++++++++++++++++++++ packages/lib/src/components/Script.tsx | 26 +-- packages/lib/src/hooks/use-script.tsx | 29 +++- packages/lib/src/utils/types-utils.ts | 1 + 4 files changed, 212 insertions(+), 15 deletions(-) create mode 100644 packages/lib/src/components/Script.test.tsx diff --git a/packages/lib/src/components/Script.test.tsx b/packages/lib/src/components/Script.test.tsx new file mode 100644 index 00000000..4450214c --- /dev/null +++ b/packages/lib/src/components/Script.test.tsx @@ -0,0 +1,171 @@ +import React, { ReactNode, useEffect, useRef } from 'react'; +import { render } from '@testing-library/react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { Script } from './Script'; +import { Entity } from '../Entity'; +import { Script as PcScript } from 'playcanvas'; +import { Application } from '../Application'; +import { SubclassOf } from '../utils/types-utils'; + +const renderWithProviders = (ui: ReactNode) => { + return render( + + + {ui} + + + ); +}; + +describe('Script Component', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv('NODE_ENV', 'development'); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('should pass props to the script instance', () => { + const speed = 2; + const str = 'test'; + const direction = [1, 0, 0]; + + class TestingScript extends PcScript { + speed: number; + direction: number[]; + str: string; + + initialize() { + expect(this.speed).toBe(speed); + expect(this.direction).toEqual(direction); + expect(this.str).toBe(str); + } + } + + renderWithProviders(