@testing-library/react#getByText TypeScript Examples

The following examples show how to use @testing-library/react#getByText. 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: QueryBuilder_StudioPlugin.test.tsx    From legend-studio with Apache License 2.0 6 votes vote down vote up
test(
  integrationTest('Open query builder by editing query of a service'),
  async () => {
    const mockedEditorStore = TEST__buildQueryBuilderMockedEditorStore();
    const renderResult = await TEST__setUpEditorWithDefaultSDLCData(
      mockedEditorStore,
      { entities },
    );

    MOBX__enableSpyOrMock();
    mockedEditorStore.graphState.globalCompileInFormMode =
      jest.fn<TEMPORARY__JestMock>();
    mockedEditorStore.graphManagerState.graphManager.lambdasToPureCode =
      jest.fn<TEMPORARY__JestMock>();
    MockedMonacoEditorInstance.getValue.mockReturnValue('');
    MOBX__disableSpyOrMock();

    await TEST__openElementFromExplorerTree('model::MyService', renderResult);
    fireEvent.click(renderResult.getByText('Execution'));
    await waitFor(() => renderResult.getByTitle('Edit query...'));
    fireEvent.click(renderResult.getByTitle('Edit query...'));

    await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER),
    );
  },
);
Example #2
Source File: index.test.tsx    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
it('renders fetching placeholder when fetching config', () => {
  const { getByText } = render(
    <MemoryRouter>
      <TestEmulatorConfigProvider config={undefined}>
        <Home />
      </TestEmulatorConfigProvider>
    </MemoryRouter>
  );
  expect(getByText('Overview Page Loading...')).not.toBeNull();
});
Example #3
Source File: base-seo.test.tsx    From gatsby-plugin-next-seo with MIT License 6 votes vote down vote up
test('displays title with titleTemplate integrated', () => {
  const template = 'Gatsby SEO';
  const overrideProps = {
    ...SEO,
    titleTemplate: `${template} | %s`,
  };
  render(<BaseSeo {...overrideProps} />);
  const title = getByText(
    document.documentElement,
    (content, element) =>
      element.tagName.toLowerCase() === 'title' && content.startsWith(template),
  );
  expect(title.innerHTML).toMatch(`${template} | ${SEO.title}`);
});
Example #4
Source File: tex.test.tsx    From nota with MIT License 6 votes vote down vote up
describe("tex", () => {
  it("can render basic tex", () => {
    let { baseElement } = render(<$>\pi</$>);
    let pi = baseElement.querySelector("span.mord.mathnormal")!;
    expect(pi.textContent).toBe("π");
  });

  it("supports definitions and references", async () => {
    let { baseElement } = render(
      <DefinitionsPlugin.Provide>
        <$>
          {texDef(["x"], ["y"])}
          {texRef(["x"], ["z"])}
        </$>
      </DefinitionsPlugin.Provide>
    );
    await waitFor(() => screen.getByText("z"));

    let def = baseElement.querySelector<HTMLElement>(`[data-def="x"]`)!;
    let ref = baseElement.querySelector<HTMLElement>(`[data-ref="x"]`)!;
    getByText(def, "y");
    getByText(ref, "z");
  });
});
Example #5
Source File: ExperimentResults.test.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
test('renders the condensed table with some analyses in non-debug mode for a Conversion Metric', async () => {
  const { container } = render(<ExperimentResults analyses={analyses} experiment={experiment} metrics={metrics} />)

  // In non-debug mode, we shouldn't have a <pre> element with the JSON.
  expect(container.querySelector('.debug-json')).toBeNull()

  // Check the table snapshot before expanding any metric.
  expect(container.querySelector('.analysis-latest-results')).toMatchSnapshot()

  // Clicking on metric_1 or metric_2 should have no effect on anything, but metric_3 should render the details.
  fireEvent.click(getByText(container, /metric_1/))
  fireEvent.click(getAllByText(container, /metric_2/)[0])
  fireEvent.click(getByText(container, /metric_3/))
  await waitFor(() => getAllByText(container, /Last analyzed/), { container })
  expect(container.querySelector('.analysis-latest-results .analysis-detail-panel')).toMatchSnapshot()
  fireEvent.click(screen.getAllByRole('button', { name: /"Observed" data/ })[0])

  expect(mockedPlot).toMatchSnapshot()
})
Example #6
Source File: AsyncDualSelectWidget.test.tsx    From ke with MIT License 6 votes vote down vote up
test('It should handle change', async () => {
  defaultProps.submitChange = jest.fn()
  const handleChange = defaultProps.submitChange
  const screen = render(<AsyncDualSelectWidget {...(defaultProps as any)} />)
  await waitFor(() => screen.findByText('test'))
  const testOption = screen.getByText('test')
  const selectButton = screen.getByText('SELECT')
  fireEvent.click(testOption)
  fireEvent.click(selectButton)
  expect(handleChange).toBeCalled()
})
Example #7
Source File: QueryBuilder_Milestoning.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
test(
  integrationTest(
    'Query builder state is properly set after processing a lambda with Business Temporal source Business Temporal target',
  ),
  async () => {
    const pluginManager = LegendQueryPluginManager.create();
    pluginManager.usePresets([new Query_GraphPreset()]).install();
    const mockedQueryStore = TEST__provideMockedLegendQueryStore({
      pluginManager,
    });
    const renderResult = await TEST__setUpQueryEditor(
      mockedQueryStore,
      TEST_MilestoningModel,
      stub_RawLambda(),
      'my::map',
      'my::runtime',
    );
    const queryBuilderState = mockedQueryStore.queryBuilderState;

    const _personClass =
      mockedQueryStore.graphManagerState.graph.getClass('my::Person');
    act(() => {
      queryBuilderState.changeClass(_personClass);
    });
    const queryBuilderSetup = await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER_SETUP),
    );
    await waitFor(() => getByText(queryBuilderSetup, 'Person'));
    await waitFor(() => getByText(queryBuilderSetup, 'map'));
    await waitFor(() => getByText(queryBuilderSetup, 'runtime'));

    act(() => {
      queryBuilderState.initialize(
        create_RawLambda(
          TEST_DATA__simpleProjectionWithBusinessTemporalSourceAndBusinessTemporalTarget.parameters,
          TEST_DATA__simpleProjectionWithBusinessTemporalSourceAndBusinessTemporalTarget.body,
        ),
      );
    });
    const projectionColumnState = guaranteeType(
      queryBuilderState.fetchStructureState.projectionState.columns[0],
      QueryBuilderSimpleProjectionColumnState,
    );
    const derivedPropertyExpressionStates =
      projectionColumnState.propertyExpressionState
        .derivedPropertyExpressionStates;

    // property replaced with derived property as it is milestoned
    expect(derivedPropertyExpressionStates.length).toBe(1);
    const parameterValues = guaranteeNonNullable(
      derivedPropertyExpressionStates[0]?.propertyExpression.parametersValues,
    );

    // default milestoning date is propagated.
    expect(parameterValues.length).toBe(2);
  },
);
Example #8
Source File: base-seo.test.tsx    From gatsby-plugin-next-seo with MIT License 5 votes vote down vote up
test('BaseSeo respects the nesting/overriding behaviour of React Helmet', () => {
  const template = 'Gatsby SEO';
  const title = 'Example Title';
  const exampleUrlBase = 'https://example.com';
  const exampleUrlOverride = 'https://examp2le.com';
  render(
    <>
      <BaseSeo
        title={title}
        titleTemplate={`${template} | %s`}
        openGraph={{ url: exampleUrlBase }}
      />
      <div>
        <div>
          <BaseSeo openGraph={{ url: exampleUrlOverride }} />
        </div>
      </div>
    </>,
  );

  // <title> tag is not overridden
  const titleElement = getByText(
    document.documentElement,
    (content, element) =>
      element.tagName.toLowerCase() === 'title' && content.startsWith(template),
  );
  expect(titleElement.innerHTML).toMatch(`${template} | ${title}`);

  // og:title is not overridden, uses fallback with titleTemplate
  const ogTitleTag = document.documentElement.querySelector(
    'meta[property="og:title"]',
  );
  expect(ogTitleTag).toBeTruthy();
  expect(ogTitleTag?.getAttribute('content')).toMatch(`${template} | ${title}`);

  // og:url is overriden
  const ogUrlTag = document.documentElement.querySelector(
    'meta[property="og:url"]',
  );
  expect(ogUrlTag).toBeTruthy();
  expect(ogUrlTag?.getAttribute('content')).toEqual(exampleUrlOverride);
});
Example #9
Source File: AsyncDualSelectWidget.test.tsx    From ke with MIT License 5 votes vote down vote up
test('It should render values from server', async () => {
  const screen = render(<AsyncDualSelectWidget {...(defaultProps as any)} />)
  await waitFor(() => screen.findByText('test'))
  expect(screen.getByText('test')).toBeDefined()
  expect(screen.getByText('peretest')).toBeDefined()
})
Example #10
Source File: DefaultExplorePage.test.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
describe('<DefaultExplorePage />', () => {
  const catalogApi: jest.Mocked<typeof catalogApiRef.T> = {
    addLocation: jest.fn(_a => new Promise(() => {})),
    getEntities: jest.fn(),
    getLocationByRef: jest.fn(),
    getLocationById: jest.fn(),
    removeLocationById: jest.fn(),
    removeEntityByUid: jest.fn(),
    getEntityByRef: jest.fn(),
    refreshEntity: jest.fn(),
    getEntityAncestors: jest.fn(),
    getEntityFacets: jest.fn(),
  };

  const Wrapper = ({ children }: { children?: React.ReactNode }) => (
    <TestApiProvider apis={[[catalogApiRef, catalogApi]]}>
      {children}
    </TestApiProvider>
  );

  beforeEach(() => {
    jest.resetAllMocks();
  });

  it('renders the default explore page', async () => {
    catalogApi.getEntities.mockResolvedValue({ items: [] });

    const { getAllByRole } = await renderInTestApp(
      <Wrapper>
        <DefaultExplorePage />
      </Wrapper>,
    );

    await waitFor(() => {
      const elements = getAllByRole('tab');
      expect(elements.length).toBe(3);
      expect(getByText(elements[0], 'Domains')).toBeInTheDocument();
      expect(getByText(elements[1], 'Groups')).toBeInTheDocument();
      expect(getByText(elements[2], 'Tools')).toBeInTheDocument();
    });
  });
});
Example #11
Source File: ExperimentResults.test.tsx    From abacus with GNU General Public License v2.0 5 votes vote down vote up
test('renders correctly for 1 analysis datapoint, statistically significant', async () => {
  const metricEstimates = {
    variations: {
      '1': Fixtures.createDistributionStats({
        top_95: 2,
        bottom_95: 1,
        mean: 1,
      }),
      '2': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
    },
    diffs: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
    ratios: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
  }
  const { container } = render(
    <ExperimentResults
      analyses={[
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.PpNaive, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.IttPure, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.MittNoCrossovers, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.MittNoSpammers, metricEstimates }),
        Fixtures.createAnalysis({
          analysisStrategy: AnalysisStrategy.MittNoSpammersNoCrossovers,
          metricEstimates,
        }),
      ]}
      experiment={experiment}
      metrics={metrics}
    />,
  )

  // Check the table snapshot before expanding any metric.
  expect(container.querySelector('.analysis-latest-results')).toMatchSnapshot()

  // Clicking on metric_1 or metric_2 should have no effect on anything, but metric_3 should render the details.
  fireEvent.click(getByText(container, /metric_1/))
  fireEvent.click(getAllByText(container, /metric_2/)[0])
  fireEvent.click(getByText(container, /metric_3/))
  await waitFor(() => getByText(container, /Last analyzed/), { container })
  expect(container.querySelector('.analysis-latest-results .analysis-detail-panel')).toMatchSnapshot()

  expect(mockedPlot).toMatchSnapshot()
})
Example #12
Source File: UMLEditor.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
test(integrationTest('Association editor'), async () => {
  await TEST__openElementFromExplorerTree('ui::TestAssociation', renderResult);
  const editPanelHeader = renderResult.getByTestId(
    LEGEND_STUDIO_TEST_ID.EDIT_PANEL__HEADER_TABS,
  );
  expect(getByText(editPanelHeader, 'TestAssociation')).not.toBeNull();
  const associationEditor = renderResult.getByTestId(
    LEGEND_STUDIO_TEST_ID.ASSOCIATION_EDITOR,
  );
  const properties = ['testClassProp', 'testClassSibling'];
  // input fields for association property name are present
  properties.forEach((t) =>
    expect(getByDisplayValue(associationEditor, t)).not.toBeNull(),
  );
  // Tagged Values
  fireEvent.click(getByText(associationEditor, 'Tagged Values'));
  await waitFor(() => getByText(associationEditor, 'ProfileTest'));
  getByDisplayValue(associationEditor, 'Association Tag');
  // Steretypes
  fireEvent.click(getByText(associationEditor, 'Stereotypes'));
  await waitFor(() => getByText(associationEditor, 'stereotype2'));
  // Back to properties
  fireEvent.click(getByText(associationEditor, 'Properties'));
  await waitFor(() => getByDisplayValue(associationEditor, 'testClassProp'));
  const inputA = getByDisplayValue(associationEditor, 'testClassProp');
  const propertyTypeA = inputA.parentElement?.parentElement
    ?.parentElement as HTMLElement;
  fireEvent.change(inputA, { target: { value: 'random' } });
  await waitFor(() => getByDisplayValue(associationEditor, 'random'));
  expect(getAllByDisplayValue(propertyTypeA, '1')).toHaveLength(2);
  expect(getByText(propertyTypeA, 'TestClass')).not.toBeNull();
  expect(getAllByRole(propertyTypeA, 'button')).toHaveLength(2);
  // sub panel property
  const inputB = getByDisplayValue(associationEditor, 'testClassSibling');
  const propertyTypeB = inputB.parentElement?.parentElement
    ?.parentElement as HTMLElement;
  const buttons = getAllByRole(propertyTypeB, 'button');
  expect(buttons).toHaveLength(2);
  expect(queryByDisplayValue(associationEditor, 'ProfileTest')).toBeNull();
  fireEvent.click(guaranteeNonNullable(buttons[1])); // navigate
  const subPropertyPanel = getByTestId(
    associationEditor,
    LEGEND_STUDIO_TEST_ID.PANEL,
  );
  getByDisplayValue(subPropertyPanel, 'association tag');
  fireEvent.click(getByText(subPropertyPanel, 'Stereotypes'));
  await waitFor(() => getByText(subPropertyPanel, 'stereotype1'));
  fireEvent.click(
    guaranteeNonNullable(queryAllByRole(subPropertyPanel, 'button')[0]),
  );
});
Example #13
Source File: ExperimentResults.test.tsx    From abacus with GNU General Public License v2.0 5 votes vote down vote up
test('renders correctly for 1 analysis datapoint, not statistically significant', async () => {
  const metricEstimates = {
    variations: {
      '1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
      '2': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
    },
    diffs: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: -1,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
    ratios: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
  }
  const { container } = render(
    <ExperimentResults
      analyses={[
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.PpNaive, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.IttPure, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.MittNoCrossovers, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.MittNoSpammers, metricEstimates }),
        Fixtures.createAnalysis({
          analysisStrategy: AnalysisStrategy.MittNoSpammersNoCrossovers,
          metricEstimates,
        }),
      ]}
      experiment={experiment}
      metrics={metrics}
    />,
  )

  // Check the table snapshot before expanding any metric.
  expect(container.querySelector('.analysis-latest-results')).toMatchSnapshot()

  // Clicking on metric_1 or metric_2 should have no effect on anything, but metric_3 should render the details.
  fireEvent.click(getByText(container, /metric_1/))
  fireEvent.click(getAllByText(container, /metric_2/)[0])
  fireEvent.click(getByText(container, /metric_3/))
  await waitFor(() => getByText(container, /Last analyzed/), { container })
  expect(container.querySelector('.analysis-latest-results .analysis-detail-panel')).toMatchSnapshot()

  expect(mockedPlot).toMatchSnapshot()
})
Example #14
Source File: ProjectConfigurationEditor.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
test(integrationTest('Test Project Dependency'), async () => {
  const editPanel = renderResult.getByTestId(
    LEGEND_STUDIO_TEST_ID.EDIT_PANEL_CONTENT,
  );
  const updateButton = getByText(editPanel, 'Update');
  fireEvent.click(getByText(editPanel, 'Project Dependencies'));

  // dependency 1
  await waitFor(() => getByText(editPanel, 'PROD-1'));
  await waitFor(() => getByText(editPanel, 'org.finos.legend:prod-1'));
  await waitFor(() => getByText(editPanel, '2.0.0'));

  // dependency 2
  await waitFor(() => getByText(editPanel, 'PROD-2'));
  await waitFor(() => getByText(editPanel, 'org.finos.legend:prod-2'));
  await waitFor(() => getByText(editPanel, '3.0.0'));

  const configState = mockedEditorStore.projectConfigurationEditorState;
  const projectDependenciesToAdd =
    configState.currentProjectConfiguration.projectDependencies.filter(
      (dep) =>
        !configState.originalConfig.projectDependencies.find(
          (originalProjDep) => originalProjDep.hashCode === dep.hashCode,
        ),
    );
  const projectDependenciesToRemove =
    configState.originalConfig.projectDependencies.filter(
      (originalProjDep) =>
        !configState.currentProjectConfiguration.projectDependencies.find(
          (dep) => dep.hashCode === originalProjDep.hashCode,
        ),
    );
  expect(updateButton.getAttribute('disabled')).toBeNull();
  expect(projectDependenciesToAdd).toHaveLength(1);
  expect(projectDependenciesToRemove).toHaveLength(1);
  expect((projectDependenciesToAdd[0] as ProjectDependency).projectId).toBe(
    'org.finos.legend:prod-1',
  );
  expect((projectDependenciesToRemove[0] as ProjectDependency).projectId).toBe(
    'PROD-1',
  );
});
Example #15
Source File: document.test.tsx    From nota with MIT License 5 votes vote down vote up
describe("document", () => {
  it("automatically puts top-level content into paragraphs", () => {
    let { baseElement } = render(
      <Document>
        {["A B", "\n", "C", "\n", "\n", "D", "\n", "\n", "E", <span key={"F"}>F</span>]}
      </Document>
    );

    let paragraphs = Array.from(
      baseElement.querySelectorAll<HTMLElement>(".nota-document-inner > p")
    );
    let contents = ["A B\nC", "D", "E<span>F</span>"];
    zipExn(paragraphs, contents).map(([p, html]) => {
      expect(p.innerHTML).toBe(html);
    });
  });

  it("turns a list of sections into a hierarchy", async () => {
    let { baseElement } = render(
      <Document>
        <TableOfContents />
        <Section>Introduction</Section>
        <p>In this paper...</p>
        <Subsection>Contributions</Subsection>
        <p>We are contributing...</p>
        <Section>Conclusion</Section>
        <p>We have shown...</p>
      </Document>
    );

    let toc = baseElement.querySelector<HTMLElement>(".toc")!;
    await waitFor(() => expect(toc.querySelector("li")).not.toBeNull());

    let [intro, conclusion] = Array.from(
      baseElement.querySelectorAll<HTMLElement>(".nota-document-inner > section")!
    );
    getByText(intro, "Introduction");
    getByText(intro, "In this paper...");
    getByText(intro, "We are contributing...");

    let contributions = intro.querySelector<HTMLElement>("section")!;
    getByText(contributions, "We are contributing...");

    getByText(conclusion, "We have shown...");

    getByText(toc, "Introduction");
    getByText(toc, "Contributions");
    getByText(toc, "Conclusion");
  });

  it("supports footnotes", async () => {
    let { baseElement } = render(
      <Document>
        This is a quick<Footnote>footnote</Footnote>. And{" "}
        <Footnote>
          <strong>another</strong>
        </Footnote>
        .
      </Document>
    );

    await waitFor(() => expect(baseElement.querySelector("sup")).not.toBeNull());

    screen.getByText("footnote");
    screen.getByText("another");
    expect(baseElement.querySelector("sup")!.textContent).toBe("0");
  });
});
Example #16
Source File: QueryBuilder_Milestoning.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
test(
  integrationTest(
    'Query builder state is properly set after processing a lambda with BiTemporal source Business Temporal target',
  ),
  async () => {
    const pluginManager = LegendQueryPluginManager.create();
    pluginManager.usePresets([new Query_GraphPreset()]).install();
    const mockedQueryStore = TEST__provideMockedLegendQueryStore({
      pluginManager,
    });
    const renderResult = await TEST__setUpQueryEditor(
      mockedQueryStore,
      TEST_MilestoningModel,
      stub_RawLambda(),
      'my::map',
      'my::runtime',
    );
    const queryBuilderState = mockedQueryStore.queryBuilderState;

    const _personClass =
      mockedQueryStore.graphManagerState.graph.getClass('my::Person1');
    act(() => {
      queryBuilderState.changeClass(_personClass);
    });
    const queryBuilderSetup = await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER_SETUP),
    );
    await waitFor(() => getByText(queryBuilderSetup, 'Person1'));
    await waitFor(() => getByText(queryBuilderSetup, 'map'));
    await waitFor(() => getByText(queryBuilderSetup, 'runtime'));

    act(() => {
      queryBuilderState.initialize(
        create_RawLambda(
          TEST_DATA__simpleProjectionWithBiTemporalSourceAndBusinessTemporalTarget.parameters,
          TEST_DATA__simpleProjectionWithBiTemporalSourceAndBusinessTemporalTarget.body,
        ),
      );
    });
    const projectionColumnState = guaranteeType(
      queryBuilderState.fetchStructureState.projectionState.columns[0],
      QueryBuilderSimpleProjectionColumnState,
    );
    const derivedPropertyExpressionStates =
      projectionColumnState.propertyExpressionState
        .derivedPropertyExpressionStates;

    // property replaced with derived property as it is milestoned
    expect(derivedPropertyExpressionStates.length).toBe(1);
    const parameterValues = guaranteeNonNullable(
      derivedPropertyExpressionStates[0]?.propertyExpression.parametersValues,
    );

    //default milestoning date is propagated.
    expect(parameterValues.length).toBe(2);
  },
);
Example #17
Source File: RPopup.test.tsx    From rlayers with ISC License 4 votes vote down vote up
describe('<RPopup>', () => {
    it('should show a popup on click', async () => {
        const map = React.createRef() as React.RefObject<RMap>;
        const feature = React.createRef() as React.RefObject<RFeature>;
        const popup = React.createRef() as React.RefObject<RPopup>;
        const comp = (
            <RMap ref={map} {...common.mapProps}>
                <ROSM />
                <RLayerVector>
                    <RFeature
                        ref={feature}
                        style={common.styles.blueDot}
                        geometry={new Point(common.coords.ArcDeTriomphe)}
                    >
                        <RPopup ref={popup} trigger={'click'} className='test-popup'>
                            <div id='target'>Popup</div>
                        </RPopup>
                    </RFeature>
                </RLayerVector>
            </RMap>
        );
        const {container, rerender} = render(comp);
        if (map.current === null) throw new Error('failed rendering map');
        expect(popup.current?.visible).toBeFalsy();
        expect(container.innerHTML).toMatchSnapshot();
        feature.current?.ol.dispatchEvent(common.createEvent('click', map.current.ol));
        rerender(comp);
        expect(popup.current?.visible).toBeTruthy();
        expect(container.innerHTML).toMatchSnapshot();
        feature.current?.ol.dispatchEvent(common.createEvent('click', map.current.ol));
        rerender(comp);
        expect(popup.current?.visible).toBeFalsy();
        expect(container.innerHTML).toMatchSnapshot();
    });
    it('should show a popup on hover', async () => {
        const map = React.createRef() as React.RefObject<RMap>;
        const feature = React.createRef() as React.RefObject<RFeature>;
        const popup = React.createRef() as React.RefObject<RPopup>;
        const comp = (
            <RMap ref={map} {...common.mapProps}>
                <ROSM />
                <RLayerVector>
                    <RFeature
                        ref={feature}
                        style={common.styles.blueDot}
                        geometry={new Point(common.coords.ArcDeTriomphe)}
                    >
                        <RPopup ref={popup} trigger={'hover'} delay={{show: 50, hide: 50}}>
                            <div id='target'>Popup</div>
                        </RPopup>
                    </RFeature>
                </RLayerVector>
            </RMap>
        );
        const {container, rerender} = render(comp);
        if (map.current === null) throw new Error('failed rendering map');
        expect(popup.current?.visible).toBeFalsy();
        expect(container.innerHTML).toMatchSnapshot();
        feature.current?.ol.dispatchEvent(common.createEvent('pointerenter', map.current.ol));
        rerender(comp);
        await new Promise((res) => {
            setTimeout(() => {
                if (map.current === null) throw new Error('failed rendering map');
                expect(popup.current?.visible).toBeTruthy();
                expect(container.innerHTML).toMatchSnapshot();
                feature.current?.ol.dispatchEvent(
                    common.createEvent('pointerleave', map.current.ol)
                );
                setTimeout(() => {
                    expect(popup.current?.visible).toBeFalsy();
                    expect(container.innerHTML).toMatchSnapshot();
                    res({});
                }, 60);
            }, 60);
        });
    });
    it('should support updating the props', async () => {
        const comp = (trigger, text) => (
            <RMap {...common.mapProps}>
                <ROSM />
                <RLayerVector>
                    <RFeature
                        style={common.styles.blueDot}
                        geometry={new Point(common.coords.ArcDeTriomphe)}
                    >
                        <RPopup trigger={trigger} delay={{show: 50, hide: 50}}>
                            <div id='target'>{text}</div>
                        </RPopup>
                    </RFeature>
                </RLayerVector>
            </RMap>
        );
        const {getByText, rerender, container, unmount} = render(comp('click', 'text1'));
        expect(getByText('text1')).toBeInstanceOf(HTMLDivElement);
        expect(container.innerHTML).toMatchSnapshot();
        rerender(comp('trigger', 'text2'));
        expect(getByText('text2')).toBeInstanceOf(HTMLDivElement);
        expect(container.innerHTML).toMatchSnapshot();
        unmount();
    });
    it('should throw an error without a Feature', () => {
        const err = console.error;
        console.error = () => undefined;
        expect(() =>
            render(
                <RMap {...common.mapProps}>
                    <ROSM />
                    <RLayerVector>
                        <RPopup trigger={'click'} className='test-popup'>
                            <div>Popup</div>
                        </RPopup>
                    </RLayerVector>
                </RMap>
            )
        ).toThrow('must be part of a');
        console.error = err;
    });
});
Example #18
Source File: index.spec.tsx    From react-terminal-ui with MIT License 4 votes vote down vote up
describe('Terminal component', () => {
  let scrollIntoViewFn: (arg?: boolean | ScrollIntoViewOptions) => void;

  beforeAll(() => {
    scrollIntoViewFn = jest.fn();
    window.HTMLElement.prototype.scrollIntoView = scrollIntoViewFn;
  })

  test('Should render prompt', () => {
    const { container } = render(<Terminal lineData={ [] } onInput={ (input: string) => '' }/>);
    expect(container.querySelectorAll('span')).toHaveLength(1);
    expect(container.querySelector('span.react-terminal-line.react-terminal-active-input[data-terminal-prompt="$"]')).not.toBeNull();
    screen.getByPlaceholderText('Terminal Hidden Input');
  });

  test('Should not render prompt if onInput prop is null or not defined', () => {
    const { container } = render(<Terminal lineData={ [{type: LineType.Output, value: 'Some terminal output'}] } onInput={ null }/>);
    // Still renders output line...
    expect(container.querySelectorAll('span.react-terminal-line')).toHaveLength(1);
    // ... but not the prompt
    expect(container.querySelector('span.react-terminal-active-input')).toBeNull();
  });

  test('Should render line data', () => {
    const lineData = [
      {type: LineType.Input, value: 'Some terminal input'},
      {type: LineType.Output, value: 'Some terminal output'}
   ];
    const { container } = render(<Terminal lineData={ lineData } onInput={ (input: string) => '' }/>);
    expect(container.querySelectorAll('span')).toHaveLength(3);
    let renderedLine = screen.getByText('Some terminal output');
    expect(renderedLine.className).toEqual('react-terminal-line');
    renderedLine = screen.getByText('Some terminal input');
    expect(renderedLine.className).toEqual('react-terminal-line react-terminal-input');
  });

  test('Input prompt should not scroll into view when component first loads', () => {
    const lineData = [
      {type: LineType.Input, value: 'Some terminal input'},
      {type: LineType.Output, value: 'Some terminal output'}
   ];
    render(<Terminal lineData={ lineData } onInput={ (input: string) => '' }/>);
    jest.runAllTimers();
    expect(scrollIntoViewFn).not.toHaveBeenCalled();
  });

  test('Should accept input and scroll into view', () => {
    const onInput = jest.fn();
    const { rerender } = render(<Terminal lineData={ [] } onInput={ onInput }/>);
    const hiddenInput = screen.getByPlaceholderText('Terminal Hidden Input');
    fireEvent.change(hiddenInput, { target: { value: 'a' } });
    expect(screen.getByText('a').className).toEqual('react-terminal-line react-terminal-input react-terminal-active-input');
    screen.getByDisplayValue('a');
    expect(onInput.mock.calls.length).toEqual(0);
    fireEvent.keyDown(hiddenInput, { key: 'Enter', code: 'Enter' });
    expect(onInput).toHaveBeenCalledWith('a');
    rerender(<Terminal lineData={ [{type: LineType.Input, value: 'a'}] } onInput={ onInput }/>)
    jest.runAllTimers();
    expect(scrollIntoViewFn).toHaveBeenCalledTimes(1);
  });

  test('Should support changing color mode', () => {
    const { container } = render(<Terminal colorMode={ ColorMode.Light } lineData={ [] } onInput={ (input: string) => '' }/>);
    expect(container.querySelector('.react-terminal-wrapper.react-terminal-light')).not.toBeNull();
  });

  test('Should focus if onInput is defined', () => {
    const { container } = render(<Terminal lineData={ [] } onInput={ (input: string) => '' }/>)
    expect(container.ownerDocument.activeElement?.nodeName).toEqual('INPUT');
    expect(container.ownerDocument.activeElement?.className).toEqual('terminal-hidden-input');
  });

  test('Should not focus if onInput is undefined', () => {
    const { container } = render(<Terminal lineData={ [] } />)
    expect(container.ownerDocument.activeElement?.nodeName).toEqual('BODY');
  });

  test('Should take starting input value', () => {
    render(<Terminal lineData={ [] } onInput={ (input: string) => '' } startingInputValue="cat file.txt " />)
    const hiddenInput = screen.getByPlaceholderText('Terminal Hidden Input');
    const renderedLine = screen.getByText('cat file.txt');
    expect(renderedLine.className).toContain('react-terminal-line');
  });
});
Example #19
Source File: ROverlay.test.tsx    From rlayers with ISC License 4 votes vote down vote up
describe('<ROverlay>', () => {
    it('should support updating the props', async () => {
        const comp = (trigger, text) => (
            <RMap {...common.mapProps}>
                <ROSM />
                <RLayerVector>
                    <RFeature
                        style={common.styles.blueDot}
                        geometry={new Point(common.coords.ArcDeTriomphe)}
                    >
                        <ROverlay>
                            <div id='target'>{text}</div>
                        </ROverlay>
                    </RFeature>
                </RLayerVector>
            </RMap>
        );
        const {getByText, rerender, container, unmount} = render(comp('click', 'text1'));
        expect(getByText('text1')).toBeInstanceOf(HTMLDivElement);
        expect(container.innerHTML).toMatchSnapshot();
        rerender(comp('trigger', 'text2'));
        expect(getByText('text2')).toBeInstanceOf(HTMLDivElement);
        expect(container.innerHTML).toMatchSnapshot();
        unmount();
    });

    it('should support removing the layer', async () => {
        const {container, rerender, unmount} = render(
            <RMap {...common.mapProps}>
                <ROSM />
                <RLayerVector>
                    <RFeature
                        style={common.styles.blueDot}
                        geometry={new Point(common.coords.ArcDeTriomphe)}
                    >
                        <ROverlay>
                            <div id='target'>text</div>
                        </ROverlay>
                    </RFeature>
                </RLayerVector>
            </RMap>
        );
        expect(container.innerHTML).toMatchSnapshot();
        rerender(
            <RMap {...common.mapProps}>
                <ROSM />
            </RMap>
        );
        expect(container.innerHTML).toMatchSnapshot();
        unmount();
    });

    it('should support autoplacement', async () => {
        const map = React.createRef() as React.RefObject<RMap>;
        const comp = (auto) => (
            <RMap ref={map} {...common.mapProps}>
                <ROSM />
                <RLayerVector>
                    <RFeature
                        style={common.styles.blueDot}
                        geometry={new Point(common.coords.ArcDeTriomphe)}
                    >
                        <ROverlay autoPosition={auto}>
                            <div id='target'>text14</div>
                        </ROverlay>
                    </RFeature>
                </RLayerVector>
            </RMap>
        );
        const {getByText, container, rerender} = render(comp(false));
        if (map.current === null) throw new Error('failed retrieving component');
        map.current.ol.getSize = () => [15, 15];

        map.current.ol.getPixelFromCoordinate = () => [5, 5];
        rerender(comp(true));
        expect(getByText('text14')).toBeInstanceOf(HTMLDivElement);
        let style = getByText('text14')?.parentElement?.style;
        if (style == null) throw new Error('failed retrieving style');
        expect(style.left).toBe('0px');
        expect(style.top).toBe('0px');
        expect(style.right).toBe('');
        expect(style.bottom).toBe('');
        expect(container.innerHTML).toMatchSnapshot();

        map.current.ol.getPixelFromCoordinate = () => [10, 10];
        rerender(comp(true));
        style = getByText('text14')?.parentElement?.style;
        if (style == null) throw new Error('failed retrieving style');
        expect(container.innerHTML).toMatchSnapshot();
        expect(style.left).toBe('');
        expect(style.top).toBe('');
        expect(style.right).toBe('0px');
        expect(style.bottom).toBe('0px');
    });
});
Example #20
Source File: ExperimentResults.test.tsx    From abacus with GNU General Public License v2.0 4 votes vote down vote up
test('A/B/n: renders correctly for 1 analysis datapoint, not statistically significant', async () => {
  const experiment = Fixtures.createExperimentFull({
    variations: [
      Fixtures.createVariation({
        variationId: 1,
        name: 'control',
        isDefault: true,
        allocatedPercentage: 40,
      }),
      Fixtures.createVariation({
        variationId: 2,
        name: 'treatment1',
        isDefault: false,
        allocatedPercentage: 40,
      }),
      Fixtures.createVariation({
        variationId: 3,
        name: 'treatment2',
        isDefault: false,
        allocatedPercentage: 20,
      }),
    ],
  })
  const metricEstimates = {
    variations: {
      '1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
      '2': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
      '3': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
    },
    diffs: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: -1,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
      '3_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: -1,
        mean: 0,
      }),
      '1_3': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
      '3_2': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: -1,
        mean: 0,
      }),
      '2_3': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
    ratios: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
      '3_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '1_3': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
      '3_2': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '2_3': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
  }
  const { container } = render(
    <ExperimentResults
      analyses={[
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.PpNaive, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.IttPure, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.MittNoCrossovers, metricEstimates }),
        Fixtures.createAnalysis({ analysisStrategy: AnalysisStrategy.MittNoSpammers, metricEstimates }),
        Fixtures.createAnalysis({
          analysisStrategy: AnalysisStrategy.MittNoSpammersNoCrossovers,
          metricEstimates,
        }),
      ]}
      experiment={experiment}
      metrics={metrics}
    />,
  )

  // Check the table snapshot before expanding any metric.
  expect(container.querySelector('.analysis-latest-results')).toMatchSnapshot()

  // Clicking on metric_1 or metric_2 should have no effect on anything, but metric_3 should render the details.
  fireEvent.click(getByText(container, /metric_1/))
  fireEvent.click(getAllByText(container, /metric_2/)[0])
  fireEvent.click(getByText(container, /metric_3/))
  await waitFor(() => getByText(container, /Last analyzed/), { container })
  expect(container.querySelector('.analysis-latest-results .analysis-detail-panel')).toMatchSnapshot()

  expect(mockedPlot).toMatchSnapshot()
})
Example #21
Source File: base-seo.test.tsx    From gatsby-plugin-next-seo with MIT License 4 votes vote down vote up
test('returns full array for default seo object', () => {
  render(<BaseSeo {...SEO} />);

  expect(document.querySelector('html')?.getAttribute('lang')).toBe(
    SEO.language,
  );

  const title = getByText(
    document.documentElement,
    (content, element) =>
      element.tagName.toLowerCase() === 'title' &&
      content.startsWith(`${SEO.title}`),
  );
  const index = document.documentElement.querySelectorAll(
    'meta[content="index,follow"]',
  );
  const description = document.documentElement.querySelectorAll(
    `meta[content="${SEO.description}"]`,
  );
  const descriptionTag = document.documentElement.querySelectorAll(
    'meta[name="description"]',
  );
  const twitterCard = document.documentElement.querySelectorAll(
    'meta[content="summary_large_image"]',
  );
  const facebookAppId = document.documentElement.querySelectorAll(
    'meta[property="fb:app_id"]',
  );
  const twitterCardTag = document.documentElement.querySelectorAll(
    'meta[name="twitter:card"]',
  );
  const twitterHandle = document.documentElement.querySelectorAll(
    `meta[content="${SEO.twitter.handle}"]`,
  );
  const twitterHandleTag = document.documentElement.querySelectorAll(
    'meta[name="twitter:creator"]',
  );
  const twitterSite = document.documentElement.querySelectorAll(
    `meta[content="${SEO.twitter.site}"]`,
  );
  const twitterSiteTag = document.documentElement.querySelectorAll(
    'meta[name="twitter:site"]',
  );
  const ogUrl = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.url}"]`,
  );
  const ogUrlTag = document.documentElement.querySelectorAll(
    'meta[property="og:url"]',
  );
  const ogType = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.type}"]`,
  );
  const ogTypeTag = document.documentElement.querySelectorAll(
    'meta[property="og:type"]',
  );
  const ogTitle = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.title}"]`,
  );
  const ogTitleTag = document.documentElement.querySelectorAll(
    'meta[property="og:title"]',
  );
  const ogDescription = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.description}"]`,
  );
  const ogDescriptionTag = document.documentElement.querySelectorAll(
    'meta[property="og:description"]',
  );
  const ogImage00 = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.images[0].url}"]`,
  );
  const ogImage01 = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.images[1].url}"]`,
  );
  const ogImage02 = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.images[2].url}"]`,
  );
  const ogImage03 = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.images[3].url}"]`,
  );
  const ogDefaultImageWidthHeight = document.documentElement.querySelectorAll(
    `meta[content="${SEO.defaultOpenGraphImageHeight}"]`,
  );
  const ogSetImageHeight = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.images[0].height}"]`,
  );
  const ogSetImageWidth = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.images[0].width}"]`,
  );
  const ogSetImageAlt = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.images[0].alt}"]`,
  );
  const ogLocale = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.locale}"]`,
  );
  const ogSiteName = document.documentElement.querySelectorAll(
    `meta[content="${SEO.openGraph.site_name}"]`,
  );

  const mobileAlternateTag = document.documentElement.querySelectorAll(
    'link[rel="alternate"][media]',
  );
  const mobileAlternateHref = document.documentElement.querySelectorAll(
    `link[href="${SEO.mobileAlternate.href}"]`,
  );
  const mobileAlternateMedia = document.documentElement.querySelectorAll(
    `link[media="${SEO.mobileAlternate.media}"]`,
  );

  expect(Array.from(mobileAlternateTag).length).toBe(1);
  expect(Array.from(mobileAlternateHref).length).toBe(1);
  expect(Array.from(mobileAlternateMedia).length).toBe(1);

  const languageAlternatesTags = document.documentElement.querySelectorAll(
    'link[rel="alternate"][hrefLang]',
  );
  expect(Array.from(languageAlternatesTags).length).toBe(
    SEO.languageAlternates.length,
  );

  SEO.languageAlternates.forEach((_, idx) => {
    const languageAlternateHref = document.documentElement.querySelectorAll(
      `link[href="${SEO.languageAlternates[idx].href}"]`,
    );
    const languageAlternateHrefLang = document.documentElement.querySelectorAll(
      `link[hrefLang="${SEO.languageAlternates[idx].hrefLang}"]`,
    );

    expect(Array.from(languageAlternateHref).length).toBe(1);
    expect(Array.from(languageAlternateHrefLang).length).toBe(1);
  });

  expect(title).toBeDefined();
  expect(Array.from(index).length).toBe(2);
  expect(Array.from(description).length).toBe(1);
  expect(Array.from(descriptionTag).length).toBe(1);
  expect(Array.from(facebookAppId).length).toBe(1);
  expect(Array.from(twitterCard).length).toBe(1);
  expect(Array.from(twitterCardTag).length).toBe(1);
  expect(Array.from(twitterHandle).length).toBe(1);
  expect(Array.from(twitterHandleTag).length).toBe(1);
  expect(Array.from(twitterSite).length).toBe(1);
  expect(Array.from(twitterSiteTag).length).toBe(1);
  expect(Array.from(ogUrl).length).toBe(1);
  expect(Array.from(ogUrlTag).length).toBe(1);
  expect(Array.from(ogType).length).toBe(1);
  expect(Array.from(ogTypeTag).length).toBe(1);
  expect(Array.from(ogTitle).length).toBe(1);
  expect(Array.from(ogTitleTag).length).toBe(1);
  expect(Array.from(ogDescription).length).toBe(1);
  expect(Array.from(ogDescriptionTag).length).toBe(1);
  expect(Array.from(ogImage00).length).toBe(1);
  expect(Array.from(ogImage01).length).toBe(1);
  expect(Array.from(ogImage02).length).toBe(1);
  expect(Array.from(ogImage03).length).toBe(1);
  expect(Array.from(ogDefaultImageWidthHeight).length).toBe(6);
  expect(Array.from(ogSetImageHeight).length).toBe(1);
  expect(Array.from(ogSetImageWidth).length).toBe(1);
  expect(Array.from(ogSetImageAlt).length).toBe(1);
  expect(Array.from(ogLocale).length).toBe(1);
  expect(Array.from(ogSiteName).length).toBe(1);
});
Example #22
Source File: ExperimentResults.test.tsx    From abacus with GNU General Public License v2.0 4 votes vote down vote up
test('renders correctly for conflicting analysis data', async () => {
  toggleDebugMode()

  const metricEstimates1 = {
    variations: {
      '1': Fixtures.createDistributionStats({
        top_95: 2,
        bottom_95: 1,
        mean: 1,
      }),
      '2': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
    },
    diffs: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
    ratios: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
  }
  const metricEstimates2 = {
    variations: {
      '1': Fixtures.createDistributionStats({
        top_95: 2,
        bottom_95: 1,
        mean: 1,
      }),
      '2': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 1,
      }),
    },
    diffs: {
      '2_1': Fixtures.createDistributionStats({
        top_95: -1,
        bottom_95: -2,
        mean: -1.4,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
    ratios: {
      '2_1': Fixtures.createDistributionStats({
        top_95: 1,
        bottom_95: 0.5,
        mean: 0,
      }),
      '1_2': Fixtures.createDistributionStats({
        top_95: 0,
        bottom_95: 0,
        mean: 0,
      }),
    },
  }

  const { container } = render(
    <ExperimentResults
      analyses={[
        Fixtures.createAnalysis({
          analysisStrategy: AnalysisStrategy.PpNaive,
          metricEstimates: metricEstimates1,
        }),
        Fixtures.createAnalysis({
          analysisStrategy: AnalysisStrategy.IttPure,
          metricEstimates: metricEstimates2,
        }),
        Fixtures.createAnalysis({
          analysisStrategy: AnalysisStrategy.MittNoCrossovers,
          metricEstimates: metricEstimates2,
        }),
        Fixtures.createAnalysis({
          analysisStrategy: AnalysisStrategy.MittNoSpammers,
          metricEstimates: metricEstimates2,
        }),
        Fixtures.createAnalysis({
          analysisStrategy: AnalysisStrategy.MittNoSpammersNoCrossovers,
          metricEstimates: metricEstimates2,
        }),
      ]}
      experiment={experiment}
      metrics={metrics}
    />,
  )

  // Check the table snapshot before expanding any metric.
  expect(container.querySelector('.analysis-latest-results')).toMatchSnapshot()

  // Clicking on metric_1 or metric_2 should have no effect on anything, but metric_3 should render the details.
  fireEvent.click(getByText(container, /metric_1/))
  fireEvent.click(getAllByText(container, /metric_2/)[0])
  fireEvent.click(getByText(container, /metric_3/))
  await waitFor(() => getByText(container, /Last analyzed/), { container })
  expect(container.querySelector('.analysis-latest-results .analysis-detail-panel')).toMatchSnapshot()

  expect(mockedPlot).toMatchSnapshot()

  toggleDebugMode()
})
Example #23
Source File: DropdownMenu.spec.tsx    From symphony-ui-toolkit with Apache License 2.0 4 votes vote down vote up
describe('DropdownMenu', () => {
  it('should render with the correct classes without crash', () => {
    const wrapper = mount(
      <DropdownMenu>
        <DropdownMenuItem>Hello world</DropdownMenuItem>
        <DropdownMenuDivider/>
        <DropdownMenuItem>Hello people</DropdownMenuItem>
      </DropdownMenu>
    )
    expect(wrapper.find('DropdownMenu').length).toBe(1);
    expect(wrapper.find('DropdownMenu').childAt(0).hasClass('tk-dropdown-menu')).toBe(true);
    expect(wrapper.find('DropdownMenuDivider').length).toBe(1);
    expect(wrapper.find('DropdownMenuDivider').find('div').hasClass('tk-dropdown-menu-divider')).toBe(true);
    expect(wrapper.find('DropdownMenuItem').length).toBe(2);
    expect(wrapper.find('DropdownMenuItem').find('div').forEach(d => d.hasClass('tk-dropdown-menu__item')));
  });

  it('should call onClose when clicking outside of it', () => {
    const close = jest.fn();
    render(
      <div>
        <div>some other div</div>
        <DropdownMenu show={true} onClose={close}>
          <DropdownMenuItem>Hello world</DropdownMenuItem>
        </DropdownMenu>
      </div>
    ) ;
    expect(screen.getByText('Hello world')).toBeDefined();
    fireEvent.click(getByText(document.body, 'some other div'));
    expect(close).toHaveBeenCalled();
  });

  it('shouldn\'t call onClose when clicking outside if show=false', () => {
    const close = jest.fn();
    render(
      <div>
        <div>some other div</div>
        <DropdownMenu show={false} onClose={close}>
          <DropdownMenuItem>Hello world</DropdownMenuItem>
        </DropdownMenu>
      </div>
    ) ;
    fireEvent.click(getByText(document.body, 'some other div'));
    expect(close).not.toHaveBeenCalled();
  });

  it('should close the menu when pressing esc key', () => {
    const close = jest.fn();
    render(
      <div>
        <div>some other div</div>
        <DropdownMenu show={true} onClose={close}>
          <DropdownMenuItem>Hello world</DropdownMenuItem>
        </DropdownMenu>
      </div>
    ) ;
    expect(screen.getByText('Hello world')).toBeDefined();
    // click to get focus
    fireEvent.click(document.body);
    fireEvent.keyUp(document.body, {key: 'Escape', code: 'Escape'});
    expect(close).toHaveBeenCalled();
  });

  it('should move focus between options by pressing arrow down/up on the current option', () => {
    render(
      <DropdownMenu show={true}>
        <DropdownMenuItem data-testid={'option_1'}>Option 1</DropdownMenuItem>
        <DropdownMenuItem data-testid={'option_2'}>Option 2</DropdownMenuItem>
      </DropdownMenu>
    )

    userEvent.type(screen.getByTestId('option_1'), specialChars.arrowDown);
    expect(screen.getByTestId('option_2')).toHaveFocus();

    userEvent.type(screen.getByTestId('option_2'), specialChars.arrowUp);
    expect(screen.getByTestId('option_1')).toHaveFocus();

    // reaches the end
    userEvent.type(screen.getByTestId('option_1'), specialChars.arrowUp);
    expect(screen.getByTestId('option_2')).toHaveFocus();
  })

  it('should call onClick when pressing enter on an option', () => {
    const onClick = jest.fn();
    render(
      <DropdownMenu show={true}>
        <DropdownMenuItem data-testid={'option_1'} onClick={onClick}>Option 1</DropdownMenuItem>
      </DropdownMenu>
    )

    userEvent.type(screen.getByTestId('option_1'), specialChars.enter);
    expect(onClick).toHaveBeenCalled();
  })

  it('shouldn\'t call onClick if menu item is loading', () => {
    const onClick = jest.fn();
    render(
      <DropdownMenu show>
        <DropdownMenuItem data-testid="option_1" onClick={onClick} loading>Option 1</DropdownMenuItem>
      </DropdownMenu>
    )

    userEvent.type(screen.getByTestId('option_1'), specialChars.enter);
    expect(onClick).not.toHaveBeenCalled();
  })
})
Example #24
Source File: QueryBuilder_FetchStructure.test.tsx    From legend-studio with Apache License 2.0 4 votes vote down vote up
test(
  integrationTest(
    'Query builder state is properly set after processing a projection lambda',
  ),
  async () => {
    const pluginManager = LegendQueryPluginManager.create();
    pluginManager.usePresets([new Query_GraphPreset()]).install();
    const mockedQueryStore = TEST__provideMockedLegendQueryStore({
      pluginManager,
    });
    const renderResult = await TEST__setUpQueryEditor(
      mockedQueryStore,
      TEST_DATA__ComplexRelationalModel,
      stub_RawLambda(),
      'model::relational::tests::simpleRelationalMapping',
      'model::MyRuntime',
    );
    const queryBuilderState = mockedQueryStore.queryBuilderState;

    const _personClass = mockedQueryStore.graphManagerState.graph.getClass(
      'model::pure::tests::model::simple::Person',
    );
    const _firmClass = mockedQueryStore.graphManagerState.graph.getClass(
      'model::pure::tests::model::simple::Firm',
    );
    const mapping = mockedQueryStore.graphManagerState.graph.getMapping(
      'model::relational::tests::simpleRelationalMapping',
    );

    act(() => {
      queryBuilderState.changeClass(_personClass);
    });
    const queryBuilderSetup = await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER_SETUP),
    );
    await waitFor(() => getByText(queryBuilderSetup, 'Person'));
    await waitFor(() =>
      getByText(queryBuilderSetup, 'simpleRelationalMapping'),
    );
    await waitFor(() => getByText(queryBuilderSetup, 'MyRuntime'));
    const treeData = guaranteeNonNullable(
      queryBuilderState.explorerState.treeData,
    );
    const rootNode = guaranteeType(
      treeData.nodes.get(treeData.rootIds[0] as string),
      QueryBuilderExplorerTreeRootNodeData,
    );

    expect(getRootSetImplementation(mapping, _personClass)).toBe(
      rootNode.mappingData.targetSetImpl,
    );
    expect(rootNode.mappingData.mapped).toBe(true);

    // simpleProjection
    act(() => {
      queryBuilderState.initialize(
        create_RawLambda(
          TEST_DATA__simpleProjection.parameters,
          TEST_DATA__simpleProjection.body,
        ),
      );
    });
    let projectionCols = await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER_PROJECTION),
    );
    const FIRST_NAME_ALIAS = 'Edited First Name';
    const LAST_NAME_ALIAS = 'Last Name';
    expect(
      await waitFor(() =>
        projectionCols.querySelector(`input[value="${FIRST_NAME_ALIAS}"]`),
      ),
    ).not.toBeNull();
    expect(
      await waitFor(() =>
        projectionCols.querySelector(`input[value="${LAST_NAME_ALIAS}"]`),
      ),
    ).not.toBeNull();
    expect(
      queryBuilderState.fetchStructureState.projectionState.columns.length,
    ).toBe(2);
    let fistNameCol = guaranteeNonNullable(
      queryBuilderState.fetchStructureState.projectionState.columns.find(
        (e) => e.columnName === FIRST_NAME_ALIAS,
      ),
    );
    const firstNameProperty = guaranteeType(
      fistNameCol,
      QueryBuilderSimpleProjectionColumnState,
    ).propertyExpressionState.propertyExpression.func;
    expect(firstNameProperty).toBe(getClassProperty(_personClass, 'firstName'));
    const lastNameCol = guaranteeNonNullable(
      queryBuilderState.fetchStructureState.projectionState.columns.find(
        (e) => e.columnName === LAST_NAME_ALIAS,
      ),
    );
    const lastNameProperty = guaranteeType(
      lastNameCol,
      QueryBuilderSimpleProjectionColumnState,
    ).propertyExpressionState.propertyExpression.func;
    expect(lastNameProperty).toBe(getClassProperty(_personClass, 'lastName'));
    expect(queryBuilderState.resultSetModifierState.limit).toBeUndefined();

    // chainedProperty
    const CHAINED_PROPERTY_ALIAS = 'Firm/Legal Name';
    act(() => {
      queryBuilderState.initialize(
        create_RawLambda(
          TEST_DATA__projectionWithChainedProperty.parameters,
          TEST_DATA__projectionWithChainedProperty.body,
        ),
      );
    });
    const projectionWithChainedPropertyCols = await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER_PROJECTION),
    );
    expect(
      await waitFor(() =>
        projectionWithChainedPropertyCols.querySelector(
          `input[value="${CHAINED_PROPERTY_ALIAS}"]`,
        ),
      ),
    ).not.toBeNull();
    expect(
      queryBuilderState.fetchStructureState.projectionState.columns.length,
    ).toBe(1);
    let legalNameCol = guaranteeNonNullable(
      queryBuilderState.fetchStructureState.projectionState.columns.find(
        (e) => e.columnName === CHAINED_PROPERTY_ALIAS,
      ),
    );
    const legalNameColProperty = guaranteeType(
      legalNameCol,
      QueryBuilderSimpleProjectionColumnState,
    ).propertyExpressionState.propertyExpression.func;
    expect(legalNameColProperty).toBe(
      getClassProperty(_firmClass, 'legalName'),
    );
    const _firmPropertyExpression = guaranteeType(
      guaranteeType(legalNameCol, QueryBuilderSimpleProjectionColumnState)
        .propertyExpressionState.propertyExpression.parametersValues[0],
      AbstractPropertyExpression,
    );
    expect(_firmPropertyExpression.func).toBe(
      getClassProperty(_personClass, 'firm'),
    );
    expect(queryBuilderState.resultSetModifierState.limit).toBeUndefined();

    // result set modifiers
    const RESULT_LIMIT = 500;
    act(() => {
      queryBuilderState.initialize(
        create_RawLambda(
          TEST_DATA__projectionWithResultSetModifiers.parameters,
          TEST_DATA__projectionWithResultSetModifiers.body,
        ),
      );
    });
    projectionCols = await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER_PROJECTION),
    );
    expect(
      await waitFor(() =>
        projectionCols.querySelector(`input[value="${FIRST_NAME_ALIAS}"]`),
      ),
    ).not.toBeNull();
    expect(
      await waitFor(() =>
        projectionCols.querySelector(`input[value="${LAST_NAME_ALIAS}"]`),
      ),
    ).not.toBeNull();
    expect(
      await waitFor(() =>
        projectionCols.querySelector(
          `input[value="${CHAINED_PROPERTY_ALIAS}"]`,
        ),
      ),
    ).not.toBeNull();
    expect(
      queryBuilderState.fetchStructureState.projectionState.columns.length,
    ).toBe(3);
    const resultSetModifierState = queryBuilderState.resultSetModifierState;
    expect(resultSetModifierState.limit).toBe(RESULT_LIMIT);
    expect(resultSetModifierState.distinct).toBe(true);
    expect(resultSetModifierState.sortColumns).toHaveLength(2);
    fistNameCol = guaranteeNonNullable(
      queryBuilderState.fetchStructureState.projectionState.columns.find(
        (e) => e.columnName === FIRST_NAME_ALIAS,
      ),
    );
    legalNameCol = guaranteeNonNullable(
      queryBuilderState.fetchStructureState.projectionState.columns.find(
        (e) => e.columnName === CHAINED_PROPERTY_ALIAS,
      ),
    );
    const firstnameSortState = guaranteeNonNullable(
      resultSetModifierState.sortColumns.find(
        (e) => e.columnState === fistNameCol,
      ),
    );
    expect(firstnameSortState.sortType).toBe(COLUMN_SORT_TYPE.ASC);
    const legalNameColSortState = guaranteeNonNullable(
      resultSetModifierState.sortColumns.find(
        (e) => e.columnState === legalNameCol,
      ),
    );
    expect(legalNameColSortState.sortType).toBe(COLUMN_SORT_TYPE.DESC);
    const queryBuilder = await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER),
    );
    fireEvent.click(
      getByTitle(queryBuilder, 'Configure result set modifiers...'),
    );
    const modal = await waitFor(() => renderResult.getByRole('dialog'));
    await waitFor(() => getByText(modal, 'Sort and Order'));
    await waitFor(() => getByText(modal, 'Eliminate Duplicate Rows'));
    await waitFor(() => getByText(modal, 'Limit Results'));
    await waitFor(() => getByText(modal, FIRST_NAME_ALIAS));
    await waitFor(() => getByText(modal, CHAINED_PROPERTY_ALIAS));
    expect(
      await waitFor(() =>
        modal.querySelector(`input[value="${RESULT_LIMIT}"]`),
      ),
    ).not.toBeNull();
    fireEvent.click(getByText(modal, 'Close'));

    // filter with simple condition
    await waitFor(() => renderResult.getByText('Add a filter condition'));
    act(() => {
      queryBuilderState.initialize(
        create_RawLambda(
          TEST_DATA__getAllWithOneConditionFilter.parameters,
          TEST_DATA__getAllWithOneConditionFilter.body,
        ),
      );
    });
    let filterValue = 'testFirstName';
    let filterPanel = await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER_FILTER),
    );
    expect(
      await waitFor(() =>
        filterPanel.querySelector(`input[value="${filterValue}"]`),
      ),
    ).not.toBeNull();
    await waitFor(() => getByText(filterPanel, 'First Name'));
    await waitFor(() => getByText(filterPanel, 'is'));
    const filterState = queryBuilderState.filterState;
    expect(filterState.nodes.size).toBe(1);
    expect(
      queryBuilderState.fetchStructureState.projectionState.columns.length,
    ).toBe(0);

    // filter with group condition
    act(() => {
      queryBuilderState.resetQueryBuilder();
      queryBuilderState.resetQuerySetup();
    });
    await waitFor(() => renderResult.getByText('Add a filter condition'));
    act(() => {
      queryBuilderState.initialize(
        create_RawLambda(
          TEST_DATA__getAllWithGroupedFilter.parameters,
          TEST_DATA__getAllWithGroupedFilter.body,
        ),
      );
    });
    filterPanel = await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER_FILTER),
    );
    await waitFor(() =>
      expect(getAllByText(filterPanel, 'is')).toHaveLength(2),
    );
    await waitFor(() => getByText(filterPanel, 'or'));
    filterValue = 'lastNameTest';
    expect(
      await waitFor(() =>
        filterPanel.querySelector(`input[value="${filterValue}"]`),
      ),
    ).not.toBeNull();
    await waitFor(() => getByText(filterPanel, 'First Name'));
    const lastNameFilterValue = 'lastNameTest';
    expect(
      await waitFor(() =>
        filterPanel.querySelector(`input[value="${lastNameFilterValue}"]`),
      ),
    ).not.toBeNull();
    await waitFor(() => getByText(filterPanel, 'Last Name'));
    expect(queryBuilderState.filterState.nodes.size).toBe(3);
    expect(
      queryBuilderState.fetchStructureState.projectionState.columns.length,
    ).toBe(0);

    // projection column with derived property
    act(() => {
      queryBuilderState.resetQueryBuilder();
      queryBuilderState.resetQuerySetup();
    });
    await waitFor(() => renderResult.getByText('Add a filter condition'));
    act(() => {
      queryBuilderState.initialize(
        create_RawLambda(
          TEST_DATA__projectWithDerivedProperty.parameters,
          TEST_DATA__projectWithDerivedProperty.body,
        ),
      );
    });
    projectionCols = await waitFor(() =>
      renderResult.getByTestId(QUERY_BUILDER_TEST_ID.QUERY_BUILDER_PROJECTION),
    );
    expect(
      await waitFor(() =>
        projectionCols.querySelector(`input[value="Full Name With Title"]`),
      ),
    ).not.toBeNull();
    await waitFor(() => getByText(projectionCols, 'Name With Title'));
    expect(
      queryBuilderState.fetchStructureState.projectionState.columns.length,
    ).toBe(1);
    fireEvent.click(
      getByTitle(projectionCols, 'Set Derived Property Argument(s)...'),
    );
    const dpModal = await waitFor(() => renderResult.getByRole('dialog'));
    await waitFor(() => getByText(dpModal, 'Derived Property'));
    await waitFor(() => getByText(dpModal, 'Name With Title'));
    await waitFor(() => getByText(dpModal, 'title'));
    expect(
      await waitFor(() => dpModal.querySelector(`input[value="Mr."]`)),
    ).not.toBeNull();
  },
);