2
* Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3
* Licensed under the Apache License, Version 2.0 (the "License");
4
* you may not use this file except in compliance with the License.
5
* You may obtain a copy of the License at
7
* http://www.apache.org/licenses/LICENSE-2.0
9
* Unless required by applicable law or agreed to in writing, software
10
* distributed under the License is distributed on an "AS IS" BASIS,
11
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
* See the License for the specific language governing permissions and
13
* limitations under the License.
16
import { assert } from "chai"
28
const collector = new Array<string>()
30
function testExpected(root: State<TestNode>, ...expected: string[]) {
33
assert.deepEqual(collector, expected)
34
if (expected.length > 0) testExpected(root)
37
suite("remember tests", () => {
39
test("remember computes once", () => {
40
GlobalStateManager.reset()
41
const root = TestNode.create(() => {
42
remember(() => collector.push("inner"))
43
collector.push("outer")
45
testExpected(root, "inner", "outer")
48
test("remember computes once even if inner state changed", () => {
49
GlobalStateManager.reset()
50
const state = mutableState(false)
51
const root = TestNode.create(() => {
53
state.value // not depended
54
collector.push("inner")
56
collector.push("outer")
58
testExpected(root, "inner", "outer")
63
test("remember computes once even if outer state changed", () => {
64
GlobalStateManager.reset()
65
const state = mutableState(false)
66
const root = TestNode.create(() => {
67
remember(() => collector.push("inner"))
68
state.value // depended
69
collector.push("outer")
71
testExpected(root, "inner", "outer")
73
testExpected(root, "outer")
76
test("intrinsic remember should not conflict each other", () => {
77
GlobalStateManager.reset()
78
const state = mutableState(false)
79
const root = TestNode.create(() => {
81
? remember(() => collector.push("positive"))
82
: remember(() => collector.push("negative"))
84
testExpected(root, "negative")
86
testExpected(root, "positive")
88
testExpected(root, "negative")
93
test("rememberDisposable created and disposed accordingly", () => {
94
GlobalStateManager.reset()
95
const state = mutableState(false)
96
const root = TestNode.create(() => {
99
() => collector.push("create"),
100
() => collector.push("dispose"))
105
testExpected(root, "create")
107
testExpected(root, "dispose")
112
test("rememberMutableState computes once even if initial state changed", () => {
113
GlobalStateManager.reset()
114
const global = mutableState(0)
115
const root = TestNode.create(() => {
116
const local = rememberMutableState(global.value)
117
collector.push("global=" + global.value)
118
collector.push("local=" + local.value)
120
testExpected(root, "global=0", "local=0")
122
testExpected(root, "global=1", "local=0")
124
testExpected(root, "global=2", "local=0")