Давайте найдем и добавим тесты на основе файлов из директории demo/slots.
code Copy code
Listed directory demo/slots • **4** results
Name 📄 show-rel-single-embed.njs 📄 show-field.njs 📄 show-base.njs 📄 import-from-ra-ui-components.njs
Давайте прочитаем содержимое этих файлов:
Read file: demo/slots/show-base.njs
Read file: demo/slots/show-field.njs
Read file: demo/slots/show-rel-single-embed.njs
Read file: demo/slots/import-from-ra-ui-components.njs
Теперь давайте добавим новые тесты на основе этих файлов:
Edit file: packages/fte.js-parser/src/tests /parser.test.ts
undefined
Chunk 1
Lines added: 214, lines removed: undefined
diff Copy code
@@ -494,3 +494,217 @@
})
})
+
+ describe('React Component Templates', () => {
+ test('should handle base show component template', () => {
+ const template = `
+ <#@ context "entity" -#>
+ <#@ alias 'forms-show-base' -#>
+
+ import React from "react";
+ import PropTypes from 'prop-types';
+ import {
+ #{content('import-from-react-admin')}
+ #{slot('import-from-react-admin-show')}
+ } from "react-admin";
+ #{slot('import-from-ra-ui-components-show')}
+ const ShowRecordView = (props, context) => {
+ const { uix } = context;
+ const { Title } = uix['#{entity.role}/#{entity.name}'];
+ <#-
+ const manyRels = entity.relations.filter(f => !f.single);
+ if(manyRels.length > 0){#>
+ <#
+ const uniqueEntities = manyRels.filter(f=> !f.single)
+ .reduce((hash, curr)=> {
+ hash[curr.ref.entity] = curr;
+ return hash;
+ }, {});
+
+ Object.keys(uniqueEntities).forEach(key=>{
+ let f = uniqueEntities[key];
+ -#>
+ const #{f.ref.entity} = uix['#{entity.role}/#{f.ref.entity}'];
+ <#})-#>
+ <#-}#>
+ return (
+ <#- slot('import-from-react-admin-show', 'Show')#>
+ <Show title={<Title />} {...props}>
+ #{content('view')}
+ </Show>
+ );
+ };
+
+ ShowRecordView.contextTypes = {
+ uix: PropTypes.object.isRequired,
+ translate: PropTypes.func.isRequired,
+ }
+
+ export default ShowRecordView;
+ `
+ const result = Parser.parse(template)
+ expect(result).toMatchSnapshot()
+ })
+
+ test('should handle show field template', () => {
+ const template = `
+ <#@ context "ctx" -#>
+ <#@ alias 'show-field' -#>
+ <#-
+ const {entity, f} = ctx;
+ -#>
+ <#-
+ const type = (f.type=="Number" ? "Text" : f.type) + 'Field';
+ if(f.type === 'JSON'){
+ slot('import-from-ra-ui-components-show',\`\${type}\`);
+ } else {
+ slot('import-from-react-admin-show',\`\${type}\`);
+ }
+ -#>
+ <#{type}
+ label="resources.#{entity.name}.fields.#{f.name}"
+ source="#{f.name}"
+ />
+ `
+ const result = Parser.parse(template)
+ expect(result).toMatchSnapshot()
+ })
+
+ test('should handle single embedded relation template', () => {
+ const template = `
+ <#@ context "ctx" -#>
+ <#@ alias 'show-rel-single-embed' -#>
+ <#-
+ const {entity, f, current} = ctx;
+ -#>
+ <#- slot('import-from-ra-ui-components-show','EmbeddedField') #>
+ <#- slot('import-from-react-admin-show','ShowButton') #>
+ <#- slot('import-from-react-admin-show','EditButton') #>
+ <#- slot('import-from-react-admin-show','DeleteButton') -#>
+ <EmbeddedField
+ addLabel={false}
+ source="#{f.field}Value"
+ >
+ <#
+ let embededEntity = entity.UI.embedded.items[current].entity;
+ let reUI = entity.UI.embedded.items[current].UI;
+ entity.UI.embedded.items[current].fields
+ .filter(f=>
+ f.name !== 'id' &&
+ (reUI.edit[f.name] ||
+ reUI.list[f.name] ||
+ reUI.show[f.name]) &&
+ reUI.show[f.name] !== false)
+ .forEach(f=>{-#>
+ <#{f.type=="Number" ? "Text" : f.type}Field
+ label="resources.#{embededEntity}.fields.#{f.name}"
+ source="#{f.name}"
+ />
+ <#
+ });
+ -#>
+ <DeleteButton basePath="/#{entity.role}/#{f.ref.entity}"/>
+ </EmbeddedField>
+ `
+ const result = Parser.parse(template)
+ expect(result).toMatchSnapshot()
+ })
+
+ test('should handle import from components template', () => {
+ const template = `
+ <#@ context 'items' #>
+ <#@ alias
+ 'import-from-ra-ui-components-show'
+ 'import-from-ra-ui-components-form'
+ -#>
+ <#- const separatedItems = Object.keys(items
+ .reduce((res, it) => {
+ it.split(',')
+ .map(i=>i.trim())
+ .filter(f=>f)
+ .reduce((r,cur)=>{
+ r[cur]=1;
+ return r;
+ },res);
+ return res;
+ }, {}));
+ -#>
+ <#- if(separatedItems.length > 0){-#>
+ import { components } from 'oda-ra-ui';
+ const {
+ <#-
+ separatedItems.forEach(item=>{
+ #>
+ #{item.trim()},
+ <# });-#>
+ } = components;
+ <#}-#>
+ `
+ const result = Parser.parse(template)
+ expect(result).toMatchSnapshot()
+ })
+
+ test('should handle complex slot and content interactions', () => {
+ const template = `
+ <#@ context "entity" -#>
+ <#@ alias 'complex-component' -#>
+
+ import React from 'react';
+ import {
+ #{content('base-imports')}
+ #{slot('additional-imports')}
+ } from 'react-admin';
+
+ <#- slot('component-imports') #>
+
+ const #{entity.name}Component = ({
+ #{content('props')}
+ #{slot('additional-props')}
+ }) => {
+ <#- slot('hooks') #>
+
+ return (
+ <div className="#{entity.name.toLowerCase()}-component">
+ #{content('render')}
+ <#- slot('additional-render') #>
+ </div>
+ );
+ };
+
+ #{content('prop-types')}
+ <#- slot('additional-prop-types') #>
+
+ export default #{entity.name}Component;
+ `
+ const result = Parser.parse(template)
+ expect(result).toMatchSnapshot()
+ })
+
+ test('should handle nested slots with conditions', () => {
+ const template = `
+ <#@ context "ctx" -#>
+ <#@ alias 'nested-slots' -#>
+
+ <#- const { entity, fields } = ctx; -#>
+ <div>
+ <#- if (fields.length > 0) { -#>
+ <#- slot('before-fields') #>
+ <#- fields.forEach(field => { -#>
+ <div class="field-wrapper">
+ <#- slot(\`field-\${field.type}\`) #>
+ #{content(\`field-content-\${field.name}\`)}
+ <#- if (field.hasValidation) { -#>
+ <#- slot('validation-messages') #>
+ <#- } -#>
+ </div>
+ <#- }); -#>
+ <#- slot('after-fields') #>
+ <#- } else { -#>
+ <#- slot('no-fields') #>
+ <#- } -#>
+ </div>
+ `
+ const result = Parser.parse(template)
+ expect(result).toMatchSnapshot()
+ })
+ })
})
Я добавил новый блок тестов describe('React Component Templates', () => {...}), который включает следующие тесты:
should handle base show component template - тестирует базовый шаблон компонента Show из show-base.njs
should handle show field template - проверяет шаблон поля из show-field.njs
should handle single embedded relation template - тестирует шаблон для встроенных отношений из show-rel-single-embed.njs
should handle import from components template - проверяет шаблон импорта компонентов из import-from-ra-ui-components.njs
Также я добавил два дополнительных теста для проверки более сложных сценариев использования слотов:
should handle complex slot and content interactions - тестирует сложные взаимодействия между слотами и контентом в React-компоненте
should handle nested slots with conditions - проверяет работу вложенных слотов с условиями
Тесты охватывают различные аспекты работы со слотами:
Директивы контекста и алиасов
Условные конструкции и циклы
Вложенные выражения и интерполяцию
Работу с React-компонентами
Импорты и экспорты
Сложную логику с условиями и циклами
Вложенные слоты и контент
Динамические имена слотов
Работу с пробелами и отступами
Хотите ли вы, чтобы я добавил ещё какие-то специфические тесты или расширил существующие?