|
| 1 | +/* |
| 2 | +Copyright 2025 New Vector Ltd. |
| 3 | +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial |
| 4 | +Please see LICENSE files in the repository root for full details. |
| 5 | +*/ |
| 6 | + |
| 7 | +import { renderHook } from "jest-matrix-react"; |
| 8 | +import { BaseViewModel } from "../BaseViewModel"; |
| 9 | +import { useCreateAutoDisposedViewModel } from "../useCreateAutoDisposedViewModel"; |
| 10 | + |
| 11 | +class TestViewModel extends BaseViewModel<{ count: number }, { initial: number }> { |
| 12 | + constructor(props: { initial: number }) { |
| 13 | + super(props, { count: props.initial }); |
| 14 | + } |
| 15 | + |
| 16 | + public increment() { |
| 17 | + const newCount = this.getSnapshot().count + 1; |
| 18 | + this.snapshot.set({ count: newCount }); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +describe("useAutoDisposedViewModel", () => { |
| 23 | + it("should return view-model", () => { |
| 24 | + const vmCreator = () => new TestViewModel({ initial: 0 }); |
| 25 | + const { result } = renderHook(() => useCreateAutoDisposedViewModel(vmCreator)); |
| 26 | + const vm = result.current; |
| 27 | + expect(vm).toBeInstanceOf(TestViewModel); |
| 28 | + expect(vm.isDisposed).toStrictEqual(false); |
| 29 | + }); |
| 30 | + |
| 31 | + it("should dispose view-model on unmount", () => { |
| 32 | + const vmCreator = () => new TestViewModel({ initial: 0 }); |
| 33 | + const { result, unmount } = renderHook(() => useCreateAutoDisposedViewModel(vmCreator)); |
| 34 | + const vm = result.current; |
| 35 | + vm.increment(); |
| 36 | + unmount(); |
| 37 | + expect(vm.isDisposed).toStrictEqual(true); |
| 38 | + }); |
| 39 | + |
| 40 | + it("should recreate view-model on react strict mode", async () => { |
| 41 | + const vmCreator = () => new TestViewModel({ initial: 0 }); |
| 42 | + const output = renderHook(() => useCreateAutoDisposedViewModel(vmCreator), { reactStrictMode: true }); |
| 43 | + const vm = output.result.current; |
| 44 | + expect(vm.isDisposed).toStrictEqual(false); |
| 45 | + }); |
| 46 | +}); |
0 commit comments