92 lines
2.6 KiB
TypeScript
92 lines
2.6 KiB
TypeScript
/*
|
|
* Copyright (c) 2024 Huawei Technologies Co.,Ltd.
|
|
*
|
|
* openInula is licensed under Mulan PSL v2.
|
|
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
|
* You may obtain a copy of Mulan PSL v2 at:
|
|
*
|
|
* http://license.coscl.org.cn/MulanPSL2
|
|
*
|
|
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
|
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
|
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
|
* See the Mulan PSL v2 for more details.
|
|
*/
|
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
// @ts-nocheck For the compiled code.
|
|
|
|
import { describe, expect } from 'vitest';
|
|
import { domTest as it } from './utils';
|
|
import { template as $$template, bindRef as $$bindRef } from '../src/dom';
|
|
import { runComponent as $$runComponent, render } from '../src/core';
|
|
|
|
describe('ref', () => {
|
|
it('should reference to dom.', ({ container }) => {
|
|
/*
|
|
* 源码:
|
|
* function App(props) {
|
|
* let ref;
|
|
* return <canvas ref={ref} width="256" height="256" />;
|
|
* }
|
|
*/
|
|
const $tmpl$ = $$template(`<canvas width="256" height="256"></canvas>`);
|
|
let ref: Node;
|
|
|
|
function App() {
|
|
return (() => {
|
|
const $div = $tmpl$();
|
|
const $ref = ref;
|
|
typeof $ref === 'function' ? $$bindRef($ref, $div) : (ref = $div);
|
|
return $div;
|
|
})();
|
|
}
|
|
|
|
render(() => $$runComponent(App, {}), container);
|
|
expect(ref).toBe(container.firstChild);
|
|
});
|
|
|
|
it('should reference to component.', ({ container }) => {
|
|
/**
|
|
* 源码:
|
|
* // App.tsx
|
|
* import Canvas from "./canvas";
|
|
*
|
|
* function App() {
|
|
* let canvas;
|
|
* return <Canvas ref={canvas} />;
|
|
* }
|
|
*
|
|
* render(() => <App />, document.getElementById("app"));
|
|
*
|
|
* // canvas.tsx
|
|
* export default function Canvas(props) {
|
|
* return <canvas ref={props.ref} width="256" height="256" />;
|
|
* }
|
|
*/
|
|
const $tmpl$ = $$template('<canvas width="256" height="256"></canvas>');
|
|
|
|
function Canvas() {
|
|
return (() => {
|
|
const $div = $tmpl$();
|
|
const $ref = canvas;
|
|
typeof $ref === 'function' ? $$bindRef($ref, $div) : (canvas = $div);
|
|
return $div;
|
|
})();
|
|
}
|
|
|
|
let canvas: Node;
|
|
|
|
function App() {
|
|
return $$runComponent(Canvas, {
|
|
ref($r: Node) {
|
|
const $ref = canvas;
|
|
typeof $ref === 'function' ? $ref($r) : (canvas = $r);
|
|
},
|
|
});
|
|
}
|
|
|
|
render(() => $$runComponent(App, {}), container);
|
|
expect(canvas).toBe(container.firstChild);
|
|
});
|
|
});
|