mobx-react#Provider TypeScript Examples

The following examples show how to use mobx-react#Provider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From generator-earth with MIT License 6 votes vote down vote up
// @ts-ignore 注释
ReactDOM.render(
    <Provider {...Store}>
        <LocaleProvider locale={zhCN}>
            <HashRouter>
                <Route component={App}/>
            </HashRouter>
        </LocaleProvider>
    </Provider>
    ,
    document.getElementById('root')
)
Example #2
Source File: FieldPermssionContainer.test.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
describe('FieldPermissionContainer', function () {

  it('FieldPermissionContainer is rendered as null if renderField is empty', async () => {
    const mainStore = {
      security: {
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        getAttributePermission: () => {}
      }
    };

    const fpc = renderer.create((
      <Provider mainStore={mainStore}>
        <FieldPermissionContainer entityName="scr$Car" propertyName="engine" renderField={() => <></>}/>
      </Provider>
    ));
    expect(fpc.toJSON()).toBeNull();
  });

});
Example #3
Source File: index.tsx    From hive with MIT License 6 votes vote down vote up
function App() {
    return (
        <div className="main-content">
            <Provider store={new Store()}>
                <Fragment>
                    <Background />
                    <Startup />
                    <Loader />
                </Fragment>
            </Provider>
        </div>
    );
}
Example #4
Source File: App.tsx    From config-generator with MIT License 6 votes vote down vote up
App: React.FC = () => {
  return (
    <Provider {...stores}>
      <ThemeProvider theme={theme}>
        <div className="App">
          <AppRouter />
        </div>
      </ThemeProvider>
    </Provider>
  );
}
Example #5
Source File: DataTable.test.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
describe('<DataTable>', () => {
  const dataTableTestRenderer = create(
    <Provider mainStore={mainStore}>
      <IntlProvider locale='en'>
        <DataTable loading={false}
                   onFilterChange={noop}
                   onSortOrderChange={noop}
                   onPaginationChange={noop}
                   entityName={'scr_Car'}
                   columnDefinitions={[
                     'manufacturer',
                     'model'
                   ]}
                   items={[
                     {manufacturer: 'AAA', model: '001', id: '1'},
                     {manufacturer: 'BBB', model: '002', id: '2'},
                   ]}
                   count={2}
        />
      </IntlProvider>
    </Provider>
  );

  const dataTableTestInstance = dataTableTestRenderer.root;

  const intlComponent = dataTableTestInstance.children[0] as ReactTestInstance;
  const mainStoreComponent = intlComponent.children[0] as ReactTestInstance;
  const metadataComponent = mainStoreComponent.children[0] as ReactTestInstance;
  const observerComponent = metadataComponent.children[0] as ReactTestInstance;
  const dataTableComponent = observerComponent.children[0] as ReactTestInstance;


  it('renders',  () => {
    expect(dataTableTestInstance).not.toBeNull();
  });

  it('wrapper has a DataTable child that has a selectedRowKeys property', () => {
    expect(dataTableComponent.instance.selectedRowKeys).not.toBeUndefined();
  })

  it('selectedRowKeys must be an empty array', () => {
    expect(dataTableComponent.instance.selectedRowKeys).toBeInstanceOf(Array);
    expect(dataTableComponent.instance.selectedRowKeys).toHaveLength(0);
  })

  it('DataTable.onRowSelectionChange must be called once after click on the row', async () => {
    // Find the rows
    const rows = dataTableComponent.findAllByProps({className: 'ant-table-row ant-table-row-level-0'})

    expect(dataTableComponent.instance.disposers.length).toBeGreaterThanOrEqual(1);
    const prevSelectedRowKeys = [...dataTableComponent.instance.selectedRowKeys];
    expect(prevSelectedRowKeys).toHaveLength(0);

    rows[0].props.onClick(new Event('click'))
    const newSelectedRowKeys = dataTableComponent.instance.selectedRowKeys;
    expect(prevSelectedRowKeys).not.toEqual(newSelectedRowKeys);
    expect(newSelectedRowKeys).toHaveLength(1);
  })

  it('DataTable.items must be the same after click on the row (row selection)', () => {
    const prevItems = dataTableComponent.instance.items;

    const rows = dataTableComponent.findAllByProps({className: 'ant-table-row ant-table-row-level-0'});
    rows[0].props.onClick(new Event('click'));

    expect(dataTableComponent.instance.items === prevItems).toBe(true);
  })
});
Example #6
Source File: JmixAppProvider.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
JmixAppProvider = ({
  apolloClient,
  jmixREST,
  children,
  retrieveRestApiToken = () => Promise.resolve(undefined),
  config,
  metadata,
  Modals
}: JmixAppProviderProps) => {
  const JmixRestConnectionContext = getContext();
  return (
    <JmixRestConnectionContext.Consumer>
      {(context = {}) => {
        if (jmixREST && context.jmixREST !== jmixREST) {
          jmixAppConfig = config;
          globalJmixREST = jmixREST;
          const {
            appName,
            storage,
            clientId,
            secret,
            obtainTokenEndpoint,
            revokeTokenEndpoint,
            locale,
            contentDisplayMode,
            graphqlEndpoint
          } = jmixAppConfig ?? {};
          mainStore = new MainStore(apolloClient, jmixREST, {
            appName,
            storage,
            clientId,
            secret,
            obtainTokenEndpoint,
            revokeTokenEndpoint,
            locale,
            contentDisplayMode,
            graphqlEndpoint
          });
          mainStoreCreateListeners.forEach((onCreate) => onCreate(mainStore));
          retrieveRestApiToken().then((restApiToken) => {
            if (restApiToken != null) {
              jmixREST.restApiToken = restApiToken;
            }
            mainStore.initialize();
          });
          context = Object.assign({}, context, {jmixREST});
        }

        if (!context.jmixREST) {
          throw new Error("jmixREST instance is not passed")
        }
        return (
          <JmixRestConnectionContext.Provider value={context}>
            <MetadataProvider metadata={normalizeMetadata(metadata)}>
              <Provider mainStore={mainStore}>
                <Modals>
                  {children}
                </Modals>
              </Provider>
            </MetadataProvider>
          </JmixRestConnectionContext.Provider>
        );
      }}
    </JmixRestConnectionContext.Consumer>
  );
}
Example #7
Source File: EntityProperty.test.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
describe('<EntityProperty>', () => {

  it('renders', () => {
    render(
      <Provider mainStore={mainStore}>
        <EntityProperty entityName={'scr_Car'} propertyName={'manufacturer'} value={'AAA'} />
      </Provider>
    );

    expect(screen.getByText('Manufacturer:')).toBeInTheDocument();
    expect(screen.getByText('AAA')).toBeInTheDocument();
  });

  it('does not show label if showLabel is false', () => {
    render(
      <Provider mainStore={mainStore}>
        <EntityProperty entityName={'scr_Car'}
                        propertyName={'manufacturer'}
                        value={'AAA'}
                        showLabel={false}
        />
      </Provider>
    );

    expect(screen.queryByText('Manufacturer:')).toBeNull();
    expect(screen.getByText('AAA')).toBeInTheDocument();
  });

  it('hides if empty value', () => {
    render(
      <Provider mainStore={mainStore}>
        <EntityProperty entityName={'scr_Car'}
                        propertyName={'manufacturer'}
                        value={''}
                        hideIfEmpty={true}
        />
      </Provider>
    );
    expect(screen.queryByText('AAA')).toBeNull();
  });

  it('renders instance name if value is object', () => {
    render(
      <Provider mainStore={mainStore}>
        <EntityProperty entityName={'scr_Car'}
                        propertyName={'garage'}
                        value={{
                          _instanceName: 'XXX',
                          id: '00001'
                        }}
        />
      </Provider>
    );

    expect(screen.getByText('Garage:')).toBeInTheDocument();
    expect(screen.getByText('XXX')).toBeInTheDocument();
  });

});
Example #8
Source File: App.tsx    From react-amis-admin with Apache License 2.0 5 votes vote down vote up
export default function():JSX.Element {
    const store = (window as any).store = MainStore.create({}, {
        fetcher: ({
            url,
            method,
            data,
            config,
            headers
        }: any) => {
            config = config || {};
            config.headers = config.headers || {};
            config.withCredentials = true;

            if (config.cancelExecutor) {
                config.cancelToken = new axios.CancelToken(config.cancelExecutor);
            }

            config.headers = headers || {};
            config.method = method;

            if (method === 'get' && data) {
                config.params = data;
            } else if (data && data instanceof FormData) {
                // config.headers = config.headers || {};
                // config.headers['Content-Type'] = 'multipart/form-data';
            } else if (data
                && typeof data !== 'string'
                && !(data instanceof Blob)
                && !(data instanceof ArrayBuffer)
            ) {
                data = JSON.stringify(data);
                // config.headers = config.headers || {};
                config.headers['Content-Type'] = 'application/json';
            }

            data && (config.data = data);
            config.url = url;
            return request(config);
        },
        isCancel: (e:any) => axios.isCancel(e),
        notify: (type: 'success' | 'error' | 'info', msg: string) => {
            toast[type] ? toast[type](msg, type === 'error' ? '系统错误' : '系统消息') : console.warn('[Notify]', type, msg);
            console.log('[notify]', type, msg);
        },
        alert,
        confirm,
        copy: (contents: string, options: any = {}) => {
            const ret = copy(contents, options);
            ret && (!options || options.shutup !== true) && toast.info('内容已拷贝到剪切板');
            return ret;
        }
    });

    return (
        <Provider store={store}>
            <RootRoute store={store} />
        </Provider>
    );
}
Example #9
Source File: Form.test.tsx    From jmix-frontend with Apache License 2.0 4 votes vote down vote up
describe('Form', () => {
  let fieldTestRenderer: ReactTestRenderer;
  const mainStore = {
    security: {
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      getAttributePermission: () => {}
    }
  };
  describe('Field component', () => {
    const fieldJSX = (<Provider mainStore={mainStore}>
      <Field entityName="test-entity-name" propertyName="test-property-name"/>;
    </Provider>)

    it('Field with only required props renders', () => {
      TestRenderer.act(() => {
        fieldTestRenderer = TestRenderer.create(fieldJSX)
      })
    });

    it('Field with only required props unmount', () => {
      TestRenderer.act(() => {
        fieldTestRenderer.unmount();
      })
    });
  });

  describe('EnumField', () => {
    const enumFieldJSX = (enumClass: string) => <EnumField enumClass={enumClass}/>

    it('EnumField renders correctly with an existing enumClass', () => {
      TestRenderer.act(() => {
        fieldTestRenderer = TestRenderer.create(enumFieldJSX('Car'));
      });

      const testInstance = fieldTestRenderer.root
      expect(testInstance.props).toHaveProperty('enumClass');
      expect(testInstance.props.enumClass).toEqual('Car');
    });

    it('EnumField unmount', () => {
      TestRenderer.act(() => {
        fieldTestRenderer.unmount();
      });
    });
  })

  describe('FormField component', () => {
    it('FormField renders correctly with required props', () => {
        TestRenderer.act(() => {
          fieldTestRenderer = TestRenderer.create(
            <Provider mainStore={mainStore}>
              <FormField entityName={'carType'} propertyName={'manufacturer'}/>
            </Provider>
          )
        })

        const testInstance = fieldTestRenderer.root;

        const props = testInstance.props.children.props


        expect(props).toHaveProperty('entityName');
        expect(props).toHaveProperty('propertyName');

        expect(props.entityName).toEqual('carType');
        expect(props.propertyName).toEqual('manufacturer');
      }
    );

    it('FormField unmounts', () => {
        TestRenderer.act(() => {
          fieldTestRenderer.unmount();
        })
      }
    )
  })

  describe('EnumField component', () => {
      it('EnumField renders correctly with required props', () => {
        TestRenderer.act(() => {
          fieldTestRenderer = TestRenderer.create(<EnumField enumClass="Car"/>)
        })

        const testInstance = fieldTestRenderer.root
        expect(testInstance.props).toHaveProperty('enumClass');
        expect(testInstance.props.enumClass).toEqual('Car');
      })

      it('EnumField unmounts', () => {
        TestRenderer.act(() => {
          fieldTestRenderer.unmount();
        })
      })
    }
  )
})