@testing-library/dom#screen TypeScript Examples

The following examples show how to use @testing-library/dom#screen. 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 exevo-pan with The Unlicense 6 votes vote down vote up
describe('<LanguagePicker />', () => {
  test('should toggle visibility', () => {
    const mockToggle = jest.fn()
    const { rerender } = renderWithProviders(
      <LanguagePicker isOpen={false} setLanguageOpen={mockToggle} />,
    )

    const toggleButton = screen.getByRole('button')
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
    expect(mockToggle).toHaveBeenCalledTimes(0)

    userEvent.click(toggleButton)
    expect(mockToggle).toHaveBeenCalledTimes(1)
    rerender(<LanguagePicker isOpen setLanguageOpen={mockToggle} />)
    expect(screen.getByRole('dialog')).toBeInTheDocument()

    userEvent.click(toggleButton)
    expect(mockToggle).toHaveBeenCalledTimes(2)
    rerender(<LanguagePicker isOpen={false} setLanguageOpen={mockToggle} />)
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
  })
})
Example #2
Source File: dxc-footer.component.spec.ts    From halstack-angular with Apache License 2.0 6 votes vote down vote up
describe("DxcFooter tests", () => {
  test("should render dxc-footer", async () => {
    const text = "© DXC Technology 2019. All rights reserved.";
    const bottom = [
      {
        href: "https://www.test.com/test",
        text: "bottom-link-text",
      },
    ];
    await render(DxcFooterComponent, {
      imports: [BackgroundProviderInnerModule, PipesModule],
      componentProperties: {
        copyright: text,
        bottomLinks: bottom,
      },
    });
    expect(screen.getByText(text)).toBeTruthy();
    expect(screen.getByText("bottom-link-text")).toBeTruthy();
  });
});
Example #3
Source File: index.test.tsx    From oasis-wallet-web with Apache License 2.0 6 votes vote down vote up
describe('<NetworkSelector  />', () => {
  let store: ReturnType<typeof configureAppStore>

  beforeEach(() => {
    store = configureAppStore()
  })

  it('should match snapshot', () => {
    const component = renderComponent(store)
    expect(component.container.firstChild).toMatchSnapshot()
  })

  it('should allow switching network', async () => {
    const dispatchSpy = jest.spyOn(store, 'dispatch')
    const component = renderComponent(store)
    expect(component.queryByTestId('active-network')).toContainHTML('toolbar.networks.local')
    userEvent.click(screen.getByTestId('network-selector'))

    await waitFor(() => expect(screen.getByText('toolbar.networks.testnet')))
    screen.getByText('toolbar.networks.testnet').click()

    expect(dispatchSpy).toHaveBeenCalledWith({
      payload: 'testnet',
      type: 'network/selectNetwork',
    })
  })
})
Example #4
Source File: jest-dom.test.ts    From vanilla-extract with MIT License 6 votes vote down vote up
describe('jest-dom', () => {
  it('should attach css to nodes', () => {
    document.body.innerHTML = `
      <div data-testid="hidden" class="${hide}">Hidden Example</div>
      <div data-testid="blackBg" class="${blackBg}">Hidden Example</div>
    `;

    expect(screen.queryByTestId('hidden')).not.toBeVisible();
    expect(screen.queryByTestId('blackBg')).toHaveStyle({
      backgroundColor: 'rgb(0, 0, 0)',
    });
  });

  // CSS vars seem to be broken in jsdom/cssom/cssstyle (whichever one is relevant here)
  // As far as I can tell the issue is not on our end
  it.skip('should support css variables', () => {
    document.body.innerHTML = `
      <div data-testid="10" class="${padding}">10 padding top</div>
      <div data-testid="20" class="${twentyTheme} ${padding}">20 padding top</div>
      <div data-testid="30" style="${assignInlineVars(vars, {
        space: '30px',
      })}" class="${padding}">20 padding top</div>
    `;

    expect(screen.queryByTestId('10')).toHaveStyle({ paddingTop: '10px' });
    expect(screen.queryByTestId('20')).toHaveStyle({ paddingTop: '20px' });
    expect(screen.queryByTestId('30')).toHaveStyle({ paddingTop: '30px' });
  });
});
Example #5
Source File: dxc-chip.component.spec.ts    From halstack-angular with Apache License 2.0 6 votes vote down vote up
describe("DxcChip tests", () => {
  test("should render dxc-chip", async () => {
    await render(`<dxc-chip label="test-chip"></dxc-chip>`, {
      imports: [BackgroundProviderModule],
      declarations: [DxcChipComponent],
    });

    expect(screen.getByText("test-chip"));
  });
});
Example #6
Source File: dxc-card.component.spec.ts    From halstack-angular with Apache License 2.0 6 votes vote down vote up
describe("DxcCardComponent tests", () => {
  test("should render dxc-card", async () => {
    const projection = "Content inside the ng-content!";
    await render(`<dxc-card>${projection}</dxc-card>`, {
      imports: [BackgroundProviderModule, DxcBoxModule],
      componentProperties: {},
      declarations: [DxcCardComponent],
    });

    expect(screen.getByText(projection));
  });

  test("dxc-card onClick", async () => {
    const projection = "Content inside the ng-content!";
    const onClickFunction = jest.fn();
    await render(
      `<dxc-card (onClick)="onClickFunction($event)">${projection}</dxc-card>`,
      {
        imports: [BackgroundProviderModule, DxcBoxModule],
        componentProperties: { onClickFunction },
        declarations: [DxcCardComponent],
      }
    );

    expect(screen.getByText(projection));
    fireEvent.click(screen.getByText(projection));
    expect(onClickFunction).toHaveBeenCalled();
  });
});
Example #7
Source File: dxc-button.component.spec.ts    From halstack-angular with Apache License 2.0 6 votes vote down vote up
describe("DxcButton tests", () => {
  test("should render dxc-button", async () => {
    await render(`<dxc-button label="test-button"></dxc-button>`, {
      imports: [BackgroundProviderModule],
      componentProperties: {},
      declarations: [DxcButtonComponent],
    });

    expect(screen.getByText("test-button"));
  });

  test("Calls correct function on click", async () => {
    const onClickFunction = jest.fn();
    await render(
      `<dxc-button label="test-button" (onClick)="onClickFunction()"></dxc-button>`,
      {
        imports: [BackgroundProviderModule],
        componentProperties: { onClickFunction },
        declarations: [DxcButtonComponent],
      }
    );
    const button = screen.getByText("test-button");
    fireEvent.click(button);
    expect(onClickFunction).toHaveBeenCalled();
  });
});
Example #8
Source File: dxc-dialog.component.spec.ts    From halstack-angular with Apache License 2.0 5 votes vote down vote up
describe("DxcDialog tests", () => {
  const projection = "Content inside the ng-content!";

  test("should render dxc-dialog", async () => {
    await render(`<dxc-dialog>${projection}</dxc-dialog>`, {
      imports: [BackgroundProviderInnerModule],
      declarations: [DxcDialogComponent],
    });

    expect(screen.getByText(projection));
  });

  test("should call onCloseClick dxc-dialog", async () => {
    const onCloseClickFunction = jest.fn();
    await render(
      `<dxc-dialog (onCloseClick)="onCloseClickFunction()">${projection}</dxc-dialog>`,
      {
        imports: [BackgroundProviderInnerModule],
        componentProperties: { onCloseClickFunction },
        declarations: [DxcDialogComponent],
      }
    );

    expect(screen.getByText(projection));
    fireEvent.click(screen.getByRole("closeIcon"));
    expect(onCloseClickFunction).toHaveBeenCalled();
  });

  test("should call onBackgroundClick dxc-dialog", async () => {
    const onCloseClickFunction = jest.fn();
    await render(
      `<dxc-dialog (onBackgroundClick)="onCloseClickFunction()">${projection}</dxc-dialog>`,
      {
        imports: [BackgroundProviderInnerModule],
        componentProperties: { onCloseClickFunction },
        declarations: [DxcDialogComponent],
      }
    );

    expect(screen.getByText(projection));
    fireEvent.click(screen.getByRole("overlay"));
    expect(onCloseClickFunction).toHaveBeenCalled();
  });
});
Example #9
Source File: dxc-dropdown.component.spec.ts    From halstack-angular with Apache License 2.0 5 votes vote down vote up
describe("DxcDropdown tests", () => {
  test("should render dxc-dropdown", async () => {
    await render(
      `<dxc-dropdown label="dropdown">,
        <dxc-dropdown-option label="Facebook"></dxc-dropdown-option>
        <dxc-dropdown-option label="Twitter"></dxc-dropdown-option>
        <dxc-dropdown-option label="Linkedin"></dxc-dropdown-option>
      </dxc-dropdown>`,
      {
        imports: [BackgroundProviderModule, DxcDropdownModule, MatMenuModule],
        declarations: [DxcDropdownComponent],
        excludeComponentDeclaration: true,
      }
    );
    expect(screen.getByText("dropdown"));
  });

  test("should render options in dxc-dropdown", async () => {
    await render(
      `<dxc-dropdown label="dropdown">,
          <dxc-dropdown-option label="Facebook"></dxc-dropdown-option>
          <dxc-dropdown-option label="Twitter"></dxc-dropdown-option>
          <dxc-dropdown-option label="Linkedin"></dxc-dropdown-option>
        </dxc-dropdown>`,
      {
        imports: [BackgroundProviderModule, DxcDropdownModule],
        declarations: [DxcDropdownComponent],
        excludeComponentDeclaration: true,
      }
    );

    expect(screen.getByText("dropdown"));
    fireEvent.click(screen.getByText("dropdown"));
    expect(screen.getByText("Facebook"));
  });

  test("options interaction in dxc-dropdown", async () => {
    const onSelect = jest.fn((i) => {});
    const optionValue = "Facebook";
    await render(
      `<dxc-dropdown (onSelectOption)="onSelect($event)" label="dropdown">,
          <dxc-dropdown-option label="Facebook" [value]="optionValue" ></dxc-dropdown-option>
          <dxc-dropdown-option label="Twitter"></dxc-dropdown-option>
          <dxc-dropdown-option label="Linkedin"></dxc-dropdown-option>
        </dxc-dropdown>`,
      {
        imports: [BackgroundProviderModule, DxcDropdownModule],
        componentProperties: {
          onSelect,
          optionValue,
        },
        declarations: [DxcDropdownComponent],
        excludeComponentDeclaration: true,
      }
    );

    expect(screen.getByText("dropdown"));
    fireEvent.click(screen.getByText("dropdown"));
    expect(screen.getByText("Facebook"));
    expect(screen.getByText("Twitter"));
    fireEvent.click(screen.getByText("Facebook"));
    expect(onSelect).toHaveBeenCalledWith("Facebook");
  });
});
Example #10
Source File: dxc-alert.component.spec.ts    From halstack-angular with Apache License 2.0 5 votes vote down vote up
describe("DxcAlertComponent tests", () => {
  test("should render default dxc-alert", async () => {
    const projection = "Content inside the ng-content!";
    await render(`  <dxc-alert>${projection}</dxc-alert>`, {
      imports: [BackgroundProviderInnerModule],
      componentProperties: {},
      declarations: [DxcAlertComponent],
    });
    expect(screen.getByText(projection));
    expect(screen.getByText("information"));
  });

  test("should render dxc-alert warning", async () => {
    const projection = "Content inside the ng-content!";
    await render(`  <dxc-alert type="warning">${projection}</dxc-alert>`, {
      imports: [BackgroundProviderInnerModule],
      componentProperties: {},
      declarations: [DxcAlertComponent],
    });
    expect(screen.getByText(projection));
    expect(screen.getByText("warning"));
  });

  test("should render dxc-alert error", async () => {
    const projection = "Content inside the ng-content!";
    await render(`<dxc-alert type="error">${projection}</dxc-alert>`, {
      imports: [BackgroundProviderInnerModule],
      componentProperties: {},
      declarations: [DxcAlertComponent],
    });
    expect(screen.getByText(projection));
    expect(screen.getByText("error"));
  });

  test("should render dxc-alert confirm", async () => {
    const projection = "Content inside the ng-content!";
    await render(`<dxc-alert type="confirm">${projection}</dxc-alert>`, {
      imports: [BackgroundProviderInnerModule],
      componentProperties: {},
      declarations: [DxcAlertComponent],
    });
    expect(screen.getByText(projection));
    expect(screen.getByText("success"));
  });

  test("should dxc-alert call onClose", async () => {
    const onCloseFunction = jest.fn();
    const projection = "Content inside the ng-content!";
    await render(
      `<dxc-alert (onClose)="onCloseFunction()">${projection}</dxc-alert>`,
      {
        imports: [BackgroundProviderInnerModule],
        componentProperties: { onCloseFunction },
        declarations: [DxcAlertComponent],
      }
    );
    expect(screen.getByText(projection));
    const closeIcon = screen.getByTestId("closeIcon");

    fireEvent.click(closeIcon);
    expect(onCloseFunction).toHaveBeenCalled();
  });
});
Example #11
Source File: dxc-header.component.spec.ts    From halstack-angular with Apache License 2.0 5 votes vote down vote up
describe("DxcHeader tests", () => {
  beforeAll(() => {
    Object.defineProperty(window, "matchMedia", {
      writable: true,
      value: jest.fn().mockImplementation(() => ({
        matches: false,
      })),
    });
  });

  test("should render dxc-header", async () => {
    await render(`<dxc-header></dxc-header>`, {
      imports: [PipesModule, BackgroundProviderInnerModule],
      componentProperties: {},
      declarations: [DxcHeaderComponent],
    });
    expect(screen.getAllByRole("img")).toBeTruthy();
  });

  test("should click on logo", async () => {
    const onClick = jest.fn();
    await render(`<dxc-header (onClick)="onClick($event)"></dxc-header>`, {
      imports: [PipesModule, BackgroundProviderInnerModule],
      componentProperties: { onClick },
      declarations: [DxcHeaderComponent],
    });
    fireEvent.click(screen.getAllByRole("img")[0]);
    expect(onClick).toHaveBeenCalled();
  });

  test("Header renders with menu", async () => {
    Object.defineProperty(window, "innerWidth", {
      configurable: true,
      value: 375,
    });
    Object.defineProperty(window, "matchMedia", {
      writable: true,
      value: jest.fn().mockImplementation(() => ({
        matches: true,
      })),
    });
    TestBed.overrideComponent(DxcHeaderComponent, {
      set: { selector: "header" },
    });
    await render(`<header isResponsive="true" isMenuVisible="true"></header>`, {
      imports: [PipesModule, BackgroundProviderInnerModule],
      componentProperties: {},
      declarations: [DxcHeaderComponent],
    });
    expect(screen.getByText("Menu"));
  });
});
Example #12
Source File: dxc-accordion.component.spec.ts    From halstack-angular with Apache License 2.0 5 votes vote down vote up
describe("DxcAccordion tests", () => {
  test("should render dxc-accordion", async () => {
    const { getByText } = await render(DxcAccordionComponent, {
      componentProperties: {
        label: "test-button",
        assistiveText: "assistiveText",
      },
      imports: [MatExpansionModule, BackgroundProviderInnerModule],
    });

    expect(getByText("test-button")).toBeTruthy();
    expect(getByText("assistiveText")).toBeTruthy();
  });

  test("defaultIsExpanded dxc-accordion", async () => {
    const projection = "Content inside the ng-content!";
    const onClickFunction = jest.fn();

    await render(
      `<dxc-accordion label="test-accordion" defaultIsExpanded="true" assistiveText="assistiveText" (onClick)="onClickFunction($event)">${projection}</dxc-accordion>`,
      {
        componentProperties: { onClickFunction },
        imports: [MatExpansionModule, BackgroundProviderInnerModule],
        declarations: [DxcAccordionComponent],
      }
    );

    expect(screen.getByText("test-accordion")).toBeTruthy();
    expect(screen.getByText("assistiveText"));

    expect(screen.getByText(projection).hidden).toBeFalsy();;
    fireEvent.click(screen.getByText("test-accordion"));
    expect(onClickFunction).toHaveBeenCalled();
    expect(screen.getByText(projection).hidden)
    fireEvent.click(screen.getByText("test-accordion"));
    expect(screen.getByText(projection).hidden).toBeFalsy();
  });

  test("controlled dxc-accordion", async () => {
    const projection = "Content inside the ng-content!";
    const onClickFunction = jest.fn();
    // TestBed.overrideComponent(DxcAccordionComponent, {
    //   set: { selector: "accordion" },
    // });
    const { getByText } = await render(
      `<dxc-accordion label="test-accordion" assistiveText="assistiveText" isExpanded="false" (onClick)="onClickFunction($event)">${projection}</dxc-accordion>`,
      {
        componentProperties: { onClickFunction },
        declarations: [DxcAccordionComponent],
        imports: [MatExpansionModule, BackgroundProviderInnerModule],
      }
    );

    expect(getByText("test-accordion")).toBeTruthy();
    expect(getByText("assistiveText"));

    expect(getByText(projection).hidden);
    fireEvent.click(getByText("test-accordion"));
    expect(onClickFunction).toHaveBeenCalled();
    expect(getByText(projection).hidden);
    fireEvent.click(getByText("test-accordion"));
    expect(getByText(projection).hidden);
  });
});
Example #13
Source File: dxc-tabbed-section.component.spec.ts    From halstack-angular with Apache License 2.0 5 votes vote down vote up
describe("DxcTabbedSection tests", () => {
  test("should render dxc-tabbed-section", async () => {
    const tabs = await render(
      `<dxc-tabbed-section [sections]="[{id:0, label: 'TAB 1', selector: 'tab1-selector'},
        {id:1, label: 'TAB 2', selector: 'tab2-selector'},
        {id:2, label: 'TAB 3', selector: 'tab3-selector'}]">
    </dxc-tabbed-section>`,
      {
        componentProperties: {},
        imports: [DxcTabbedSectionModule],
        excludeComponentDeclaration: true,
      }
    );
    tabs.detectChanges();
    expect(screen.getByText("TAB 1")).toBeTruthy();
    expect(screen.getByText("TAB 2")).toBeTruthy();
    expect(screen.getByText("TAB 3")).toBeTruthy();
  });

  test("should render content dxc-tabbed-section", async () => {
    const tabs = await render(
      `<dxc-tabbed-section [sections]="[{id:0, label: 'TAB 1', selector: 'tab1-selector'},
          {id:1, label: 'TAB 2', selector: 'tab2-selector'},
          {id:2, label: 'TAB 3', selector: 'tab3-selector'}]">
      <div id="section1-selector0" style="height: 200px;">Section 1</div>
      <div id="section2-selector1" style="height: 200px;">Section 2</div>
      <div id="section3-selector2" style="height: 200px;">Section 3</div>
      </dxc-tabbed-section>`,
      {
        componentProperties: {},
        imports: [DxcTabbedSectionModule],
        excludeComponentDeclaration: true,
      }
    );
    tabs.detectChanges();
    expect(screen.getByText("Section 1")).toBeTruthy();
    expect(screen.getByText("Section 2")).toBeTruthy();
    expect(screen.getByText("Section 3")).toBeTruthy();
  });
});
Example #14
Source File: dxc-heading.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcHeading tests", () => {
  test("should render heading level 1", async () => {
    await render(DxcHeadingComponent, {
      componentProperties: { level: 1, text: "heading1" },
      declarations: [DxcHeadingComponent],
    });

    expect(screen.getByText("heading1"));
    expect(screen.getByRole("heading").textContent).toEqual("heading1");
    expect(screen.getByRole("heading", { level: 1 })).toBeInTheDocument();
  });

  test("should render heading level 2", async () => {
    await render(DxcHeadingComponent, {
      componentProperties: { level: 2, text: "heading2" },
    });

    expect(screen.getByText("heading2"));
    expect(screen.getByRole("heading").textContent).toEqual("heading2");
    expect(screen.getByRole("heading", { level: 2 })).toBeInTheDocument();
  });

  test("should render heading level 3", async () => {
    await render(DxcHeadingComponent, {
      componentProperties: { level: 3, text: "heading3" },
    });

    expect(screen.getByText("heading3"));
    expect(screen.getByRole("heading").textContent).toEqual("heading3");
    expect(screen.getByRole("heading", { level: 3 })).toBeInTheDocument();
  });

  test("should render heading level 4", async () => {
    await render(DxcHeadingComponent, {
      componentProperties: { level: 4, text: "heading4" },
    });

    expect(screen.getByText("heading4"));
    expect(screen.getByRole("heading").textContent).toEqual("heading4");
    expect(screen.getByRole("heading", { level: 4 })).toBeInTheDocument();
  });

  test("should render heading level 5", async () => {
    await render(DxcHeadingComponent, {
      componentProperties: { level: 5, text: "heading5" },
    });

    expect(screen.getByText("heading5"));
    expect(screen.getByRole("heading").textContent).toEqual("heading5");
    expect(screen.getByRole("heading", { level: 5 })).toBeInTheDocument();
  });

  test("should render heading level 1 and tag h3", async () => {
    await render(DxcHeadingComponent, {
      componentProperties: {
        level: 1,
        text: "heading1 as tag h3",
        asTag: "h3",
      },
    });

    expect(screen.getByText("heading1 as tag h3"));
    expect(screen.getByRole("heading", { level: 3 })).toBeInTheDocument();
  });
  test("should render heading level 2 and tag h4", async () => {
    await render(DxcHeadingComponent, {
      componentProperties: {
        level: 2,
        text: "heading2 as tag h4",
        asTag: "h4",
      },
    });

    expect(screen.getByText("heading2 as tag h4"));
    expect(screen.getByRole("heading", { level: 4 })).toBeInTheDocument();
  });

  test("should render heading level 3 and tag h5", async () => {
    await render(DxcHeadingComponent, {
      componentProperties: {
        level: 3,
        text: "heading3 as tag h5",
        asTag: "h5",
      },
    });

    expect(screen.getByText("heading3 as tag h5"));
    expect(screen.getByRole("heading", { level: 5 })).toBeInTheDocument();
  });

  test("should render heading level 4 and tag h2", async () => {
    await render(DxcHeadingComponent, {
      componentProperties: {
        level: 4,
        text: "heading4 as tag h2",
        asTag: "h2",
      },
    });

    expect(screen.getByText("heading4 as tag h2"));
    expect(screen.getByRole("heading", { level: 2 })).toBeInTheDocument();
  });

  test("should render heading level 5 and tag h1", async () => {
    await render(DxcHeadingComponent, {
      componentProperties: {
        level: 5,
        text: "heading5 as tag h1",
        asTag: "h1",
      },
    });

    expect(screen.getByText("heading5 as tag h1"));
    expect(screen.getByRole("heading", { level: 1 })).toBeInTheDocument();
  });
});
Example #15
Source File: dxc-upload.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcUpload tests", () => {
  test("should render dxc-upload", async () => {
    const { getByText } = await render(DxcUploadComponent, {
      componentProperties: {},
      excludeComponentDeclaration: true,
      imports: [DxcUploadModule],
    });

    expect(getByText("There are no files to upload"));
  });

  test("should input a file dxc-upload", async () => {
    const dxcUpload = await render(DxcUploadComponent, {
      componentProperties: {},
      excludeComponentDeclaration: true,
      imports: [DxcUploadModule],
    });
    dxcUpload.detectChanges();

    const inputEl = dxcUpload.getByTestId("fileInput");
    const file = new File(["foo"], "foo.txt", {
      type: "text/plain",
    });

    fireEvent.change(inputEl, { target: { files: [file] } });
    dxcUpload.detectChanges();
    await waitFor(() => {
      dxcUpload.detectChanges();
      screen.getByTestId("filesToUpload");
      expect(screen.getByText("foo.txt"));
    });
  });

  test("function callback in dxc-upload", async () => {
    const fileUpload = jest.fn((file) => {
      const result = new Promise((resolve) => setTimeout(resolve, 8000));
      return result;
    });

    const dxcUpload = await render(DxcUploadComponent, {
      componentProperties: { uploadCallback: fileUpload },
      excludeComponentDeclaration: true,
      imports: [DxcUploadModule],
    });
    dxcUpload.detectChanges();

    const inputEl = dxcUpload.getByTestId("fileInput");
    const file = new File(["foo"], "foo.txt", {
      type: "text/plain",
    });

    fireEvent.change(inputEl, { target: { files: [file] } });
    dxcUpload.detectChanges();
    await waitFor(() => {
      dxcUpload.detectChanges();
      screen.getByTestId("filesToUpload");
      expect(screen.getByText("foo.txt"));
      fireEvent.click(screen.getByText("Upload"));
      expect(fileUpload).toHaveBeenCalledWith({
        status: "processing",
        fileData: file,
        image: null,
      });
    });
  });

  test("function callback multiple times in dxc-upload", async () => {
    const fileUpload = jest.fn((file) => {
      const result = new Promise((resolve) => setTimeout(resolve, 8000));
      return result;
    });

    const dxcUpload = await render(DxcUploadComponent, {
      componentProperties: { uploadCallback: fileUpload },
      excludeComponentDeclaration: true,
      imports: [DxcUploadModule],
    });
    dxcUpload.detectChanges();

    const inputEl = dxcUpload.getByTestId("fileInput");
    const file = new File(["foo"], "foo.txt", {
      type: "text/plain",
    });

    const file2 = new File(["(⌐□_□)"], "chucknorris.txt", {
      type: "text/plain",
    });

    fireEvent.change(inputEl, { target: { files: [file, file2] } });
    dxcUpload.detectChanges();
    await waitFor(() => {
      dxcUpload.detectChanges();
      screen.getByTestId("filesToUpload");
      expect(screen.getByText("foo.txt"));
      expect(screen.getByText("chucknorris.txt"));
      fireEvent.click(screen.getByText("Upload"));
      expect(fileUpload).toHaveBeenCalledTimes(2);
    });
  });
});
Example #16
Source File: dxc-textarea.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcTextareaComponent", () => {
  test("should render dxc-text-input", async () => {
    const input = await render(DxcTextareaComponent, {
      componentProperties: {
        label: "test-input",
        helperText: "helper-text",
      },
      imports: [CommonModule, FormsModule],
    });

    expect(input.getByText("test-input"));
    expect(input.getByText("helper-text"));
  });
  test("Renders with correct label", async () => {
    const input = await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
      },
      imports: [CommonModule, FormsModule],
    });
    expect(input.getByText("Example label")).toBeTruthy();
  });
  test("Renders with correct label and helper text", async () => {
    const input = await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        helperText: "Example helper text",
      },
      imports: [CommonModule, FormsModule],
    });
    expect(input.getByText("Example label")).toBeTruthy();
    expect(input.getByText("Example helper text")).toBeTruthy();
  });
  test("Renders with correct label and optional", async () => {
    const input = await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        helperText: "Example helper text",
        optional: true,
      },
      imports: [CommonModule, FormsModule],
    });
    expect(input.getByText("Example label")).toBeTruthy();
    expect(input.getByText("(Optional)")).toBeTruthy();
    expect(input.getByText("Example helper text")).toBeTruthy();
  });
  test("Renders with correct placeholder", async () => {
    await render(DxcTextareaComponent, {
      componentProperties: {
        placeholder: "Placeholder",
      },
      imports: [CommonModule, FormsModule],
    });
    const input = <HTMLInputElement>screen.getByRole("textbox");
    expect(input.getAttribute("placeholder")).toBe("Placeholder");
  });
  test("Renders with error message", async () => {
    await render(DxcTextareaComponent, {
      componentProperties: {
        error: "Error message",
      },
      imports: [CommonModule, FormsModule],
    });
    expect(screen.getByText("Error message")).toBeTruthy();
  });
  test("Renders with correct default rows", async () => {
    await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        rows: 10,
      },
      imports: [CommonModule, FormsModule],
    });
    const textarea = <HTMLInputElement>screen.getByLabelText("Example label");
    expect(textarea.getAttribute("rows")).toBe("10");
  });
  test("Strict mode - Pattern constraint", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        placeholder: "Placeholder",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
        margin: "medium",
        pattern: '^.*(?=.*[a-zA-Z])(?=.*\\d)(?=.*[!&$%&? "]).*$',
        optional: true,
      },
      imports: [CommonModule, FormsModule],
    });
    const textarea = <HTMLInputElement>(
      screen.getByLabelText("Example label (Optional)")
    );

    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "new value" } });
    expect(onChange).toHaveBeenCalledWith({
      value: "new value",
      error: "Please use a valid pattern",
    });
    fireEvent.blur(textarea);
    expect(onBlur).toHaveBeenCalledWith({
      error: "Please use a valid pattern",
      value: "new value",
    });
    expect(screen.getByDisplayValue("new value"));
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "pattern4&" } });
    expect(onChange).toHaveBeenCalledWith({
      error: undefined,
      value: "pattern4&",
    });
    fireEvent.blur(textarea);
    expect(onBlur).toHaveBeenCalledWith({
      error: undefined,
      value: "pattern4&",
    });
    expect(screen.getByDisplayValue("pattern4&"));
  });
  test("Strict mode - Length constraint", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        placeholder: "Placeholder",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
        margin: "medium",
        minLength: 5,
        maxLength: 10,
        optional: true,
      },
      imports: [CommonModule, FormsModule],
    });
    const textarea = <HTMLInputElement>(
      screen.getByLabelText("Example label (Optional)")
    );
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "test" } });
    fireEvent.blur(textarea);
    await waitFor(() => {
      expect(onBlur).toHaveBeenCalledWith({
        error: "Min length 5, Max length 10",
        value: "test",
      });
    });
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "test 2" } });
    fireEvent.blur(textarea);
    await waitFor(() => {
      expect(onBlur).toHaveBeenCalledWith({
        error: undefined,
        value: "test 2",
      });
    });
  });
  test("Strict mode - Pattern and length constraints", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        placeholder: "Placeholder",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
        margin: "medium",
        pattern: '^.*(?=.*[a-zA-Z])(?=.*\\d)(?=.*[!&$%&? "]).*$',
        minLength: 5,
        maxLength: 10,
        optional: true,
      },
      imports: [CommonModule, FormsModule],
    });
    const textarea = <HTMLInputElement>(
      screen.getByLabelText("Example label (Optional)")
    );

    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "test" } });
    fireEvent.blur(textarea);
    expect(onBlur).toHaveBeenCalledWith({
      error: "Min length 5, Max length 10",
      value: "test",
    });
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "test " } });
    fireEvent.blur(textarea);
    expect(onBlur).toHaveBeenCalledWith({
      error: "Please use a valid pattern",
      value: "test ",
    });
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "test 4" } });
    fireEvent.blur(textarea);
    expect(onBlur).toHaveBeenCalledWith({ error: undefined, value: "test 4" });
  });
  test("Non Strict mode - Pattern constraint", async () => {
    const onChange = jest.fn((value) => {
      expect(value.value).toBe("Example value");
    });
    const onBlur = jest.fn(({ value, error }) => {
      expect(value).toBe("Example value");
      expect(error).toBe("Please use a valid pattern");
    });
    await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        placeholder: "Placeholder",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
        margin: "medium",
        pattern: '^.*(?=.*[a-zA-Z])(?=.*d)(?=.*[!&$%&? "]).*$',
        optional: true,
      },
      imports: [CommonModule, FormsModule],
    });
    const textarea = <HTMLInputElement>(
      screen.getByLabelText("Example label (Optional)")
    );
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "Example value" } });
    fireEvent.blur(textarea);
  });
  test("Non Strict mode - Length constraint", async () => {
    const onChange = jest.fn((value) => {
      expect(value.value).toBe("Example value");
    });
    const onBlur = jest.fn(({ value, error }) => {
      expect(value).toBe("Example value");
      expect(error).toBe("Min length 5, Max length 10");
    });
    await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        placeholder: "Placeholder",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
        margin: "medium",
        minLength: 5,
        maxLength: 10,
        optional: true,
      },
      imports: [CommonModule, FormsModule],
    });
    const textarea = <HTMLInputElement>(
      screen.getByLabelText("Example label (Optional)")
    );
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "Example value" } });
    fireEvent.blur(textarea);
  });
  test("Non Strict mode - Pattern and length constraints", async () => {
    const onChange = jest.fn((value) => {
      expect(value.value).toBe("Example value");
    });
    const onBlur = jest.fn(({ value, error }) => {
      expect(value).toBe("Example value");
      expect(error).toBe("Min length 5, Max length 10");
    });
    await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        placeholder: "Placeholder",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
        margin: "medium",
        minLength: 5,
        maxLength: 10,
        optional: true,
      },
      imports: [CommonModule, FormsModule],
    });
    const textarea = <HTMLInputElement>(
      screen.getByLabelText("Example label (Optional)")
    );
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "Example value" } });
    fireEvent.blur(textarea);
  });
  test("onBlur function is called correctly", async () => {
    const onBlur = jest.fn();
    await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        onBlur: {
          emit: onBlur,
        } as any,
        optional: true,
      },
      imports: [CommonModule, FormsModule],
    });
    const textarea = <HTMLInputElement>(
      screen.getByLabelText("Example label (Optional)")
    );
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "Blur test" } });
    fireEvent.blur(textarea);
    expect(onBlur).toHaveBeenCalled();
    expect(onBlur).toHaveBeenCalledWith({
      value: "Blur test",
      error: undefined,
    });
  });
  test("Controlled textarea", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        value: "test",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
        margin: "medium",
        optional: true,
      },
      imports: [CommonModule, FormsModule],
    });
    const textarea = <HTMLInputElement>(
      screen.getByLabelText("Example label (Optional)")
    );
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "Controlled test" } });
    await waitFor(() => {
      expect(screen.getByDisplayValue("test"));
      expect(onChange).toHaveBeenCalledWith({
        value: "Controlled test",
        error: undefined,
      });
    });
    fireEvent.blur(textarea);
    await waitFor(() => {
      expect(onBlur).toHaveBeenCalled();
      expect(onBlur).toHaveBeenCalledWith({ value: "test", error: undefined });
    });
  });
  test("Uncontrolled input", async () => {
    const onChange = jest.fn();
    await render(DxcTextareaComponent, {
      componentProperties: {
        label: "Example label",
        defaultValue: "test",
        onChange: {
          emit: onChange,
        } as any,
        optional: true,
      },
      imports: [CommonModule, FormsModule],
    });
    const textarea = <HTMLInputElement>(
      screen.getByLabelText("Example label (Optional)")
    );
    expect(screen.getByDisplayValue("test"));
    textarea.focus();
    expect(textarea).toHaveFocus();
    fireEvent.click(textarea);
    fireEvent.input(textarea, { target: { value: "Uncontrolled test" } });
    expect(onChange).toHaveBeenCalled();
    expect(onChange).toHaveBeenCalledWith({
      value: "Uncontrolled test",
      error: undefined,
    });
    expect(textarea.value).toBe("Uncontrolled test");
  });
});
Example #17
Source File: dxc-text-input.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcNewTextInputComponent", () => {
  test("should render dxc-text-input", async () => {
    const input = await render(DxcTextInputComponent, {
      componentProperties: {
        label: "test-input",
        helperText: "helper-text",
      },
      imports: [CommonModule, FormsModule],
      providers: [DxcTextInputService],
      declarations: [FilterOptionsPipe, BoldOptionsPipe],
    });

    expect(input.getByText("test-input"));
    expect(input.getByText("helper-text"));
  });

  test("should render error dxc-text-input", async () => {
    const input = await render(DxcTextInputComponent, {
      componentProperties: {
        label: "test-input",
        helperText: "helper-text",
        error: "Very important error",
      },
      imports: [CommonModule, FormsModule],
      providers: [DxcTextInputService],
      declarations: [FilterOptionsPipe, BoldOptionsPipe],
    });

    expect(input.getByText("test-input"));
    expect(input.getByText("helper-text"));
    expect(input.getByText("Very important error"));
    expect(input.getByLabelText("Error"));
  });

  test("should show options", async () => {
    const input = await render(
      `<dxc-text-input
        placeholder="placeholder"
        label="Input label"
        helperText="helper text"
        margin="small"
        clearable="true"
        [suggestions]="[
          'Albania',
          'Andorra',
          'Belgium'
        ]"
      ></dxc-text-input>`,
      {
        imports: [CommonModule, FormsModule],
        providers: [DxcTextInputService],
        declarations: [
          FilterOptionsPipe,
          BoldOptionsPipe,
          DxcTextInputComponent,
        ],
      }
    );

    expect(input.getByText("Input label"));
    expect(input.getByText("helper text"));
    expect(input.getByText("Albania"));
    expect(input.getByText("Andorra"));
    expect(input.getByText("Belgium"));
  });

  test("should filter options", async () => {
    await render(
      `<dxc-text-input
        label="Input label"
        helperText="helper text"
        value="Belgium"
        margin="small"
        clearable="true"
        [suggestions]="[
          'Albania',
          'Andorra',
          'Belgium'
        ]"
      ></dxc-text-input>`,
      {
        imports: [CommonModule, FormsModule],
        providers: [DxcTextInputService],
        declarations: [
          FilterOptionsPipe,
          BoldOptionsPipe,
          DxcTextInputComponent,
        ],
      }
    );

    expect(screen.getByText("Input label"));
    expect(screen.getByText("helper text"));
    const text1 = screen.queryByText("Albania");
    const text2 = screen.queryByText("Andorra");
    expect(text1).toBeNull();
    expect(text2).toBeNull();
    expect(screen.getByDisplayValue("Belgium")).toBeTruthy();
  });

  test("should clear input", async () => {
    const onChange = jest.fn();
    const input = await render(
      `<dxc-text-input
        placeholder="placeholder"
        label="Input label"
        helperText="helper text"
        margin="small"
        value="test input value"
        clearable="true"
        (onChange)="onChange($event)"
        optional="true"
      ></dxc-text-input>`,
      {
        imports: [CommonModule, FormsModule],
        providers: [DxcTextInputService],
        declarations: [
          FilterOptionsPipe,
          BoldOptionsPipe,
          DxcTextInputComponent,
        ],
        componentProperties: { onChange },
      }
    );

    expect(input.getByText("Input label"));
    expect(input.getByText("helper text"));
    expect(screen.getByDisplayValue("test input value")).toBeTruthy();
    fireEvent.click(input.getByLabelText("Clear"));
    expect(onChange).toHaveBeenCalledWith({ value: "", error: undefined });
  });

  test("should allow interaction with action button", async () => {
    const click = jest.fn();
    const input = await render(
      `<dxc-text-input
        placeholder="placeholder"
        label="Input label"
        helperText="helper text"
        margin="small"
        value="controlledValue"
        clearable="true"
        (onActionClick)="click()"
      >
        <dxc-text-input-action>
          <svg
            id="highlight_off_black_18dp"
            xmlns="http://www.w3.org/2000/svg"
            width="18"
            height="18"
            viewBox="0 0 18 18"
          >
            <path
              id="Path_2943"
              data-name="Path 2943"
              d="M0,0H18V18H0Z"
              fill="none"
            />
            <path
              id="Path_2944"
              data-name="Path 2944"
              d="M10,4a6,6,0,1,0,6,6A6.01,6.01,0,0,0,10,4Zm3,7.945L11.945,13,10,11.06,8.059,13,7,11.945,8.944,10,7,8.059,8.059,7,10,8.944,11.945,7,13,8.059,11.06,10Z"
              transform="translate(-1.002 -1.002)"
              fill="#ffe6e9"
            />
            <path
              id="Path_2945"
              data-name="Path 2945"
              d="M11.444,6.5,9.5,8.443,7.558,6.5,6.5,7.558,8.443,9.5,6.5,11.444,7.558,12.5,9.5,10.558,11.444,12.5,12.5,11.444,10.558,9.5,12.5,7.558ZM9.5,2A7.5,7.5,0,1,0,17,9.5,7.494,7.494,0,0,0,9.5,2Zm0,13.5a6,6,0,1,1,6-6A6.009,6.009,0,0,1,9.5,15.5Z"
              transform="translate(-0.501 -0.501)"
              fill="#d0011b"
            />
          </svg>
        </dxc-text-input-action>
      </dxc-text-input>`,
      {
        imports: [CommonModule, FormsModule],
        providers: [DxcTextInputService, DxcTextInputActionComponent],
        declarations: [
          DxcTextInputComponent,
          FilterOptionsPipe,
          BoldOptionsPipe,
          DxcTextInputActionComponent,
        ],
        componentProperties: { click },
      }
    );

    fireEvent.click(input.getByLabelText("Action"));
    expect(click).toHaveBeenCalled();
  });

  test("should not allow interation with disabled input", async () => {
    const onChange = jest.fn();
    const input = await render(
      `<dxc-text-input
        placeholder="placeholder"
        label="Input label"
        helperText="helper text"
        margin="small"
        value="test input value"
        disabled="true"
        (onChange)="onChange($event)"
      ></dxc-text-input>`,
      {
        imports: [CommonModule, FormsModule],
        providers: [DxcTextInputService],
        declarations: [
          DxcTextInputComponent,
          FilterOptionsPipe,
          BoldOptionsPipe,
        ],
        componentProperties: { onChange },
      }
    );

    expect(input.getByText("Input label"));
    expect(input.getByText("helper text"));
    expect(screen.getByDisplayValue("test input value")).toBeTruthy();
    fireEvent.click(input.getByRole("textbox"));
    expect(onChange).not.toHaveBeenCalledWith({ value: "", error: undefined });
  });

  test("controlled dxc-input-text input change and blur", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextInputComponent, {
      componentProperties: {
        label: "Input label",
        value: "initial",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
      },
      imports: [CommonModule, FormsModule],
      providers: [DxcTextInputService],
      declarations: [FilterOptionsPipe, BoldOptionsPipe],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    fireEvent.click(input);
    expect(screen.getByDisplayValue("initial"));
    fireEvent.input(input, { target: { value: "new value" } });
    expect(onChange).toHaveBeenCalledWith({ value: "new value", error: undefined });
    fireEvent.blur(input);
    expect(onBlur).toHaveBeenCalledWith({ error: undefined, value: "initial" });
    await waitFor(() => {
      expect(screen.getByDisplayValue("initial"));
    });
  });

  test("uncontrolled dxc-input-text input change and blur", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextInputComponent, {
      componentProperties: {
        label: "Input label",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
      },
      imports: [CommonModule, FormsModule],
      providers: [DxcTextInputService],
      declarations: [FilterOptionsPipe, BoldOptionsPipe],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    fireEvent.click(input);
    expect(screen.getByDisplayValue(""));
    fireEvent.input(input, { target: { value: "new value" } });
    expect(onChange).toHaveBeenCalledWith({ value: "new value", error: undefined });
    fireEvent.blur(input);
    expect(onBlur).toHaveBeenCalledWith({ error: undefined, value: "new value" });
    await waitFor(() => {
      expect(screen.getByDisplayValue("new value"));
    });
  });

  test("uncontrolled with defaultValue", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextInputComponent, {
      componentProperties: {
        label: "Input label",
        defaultValue: "Default value",
      },
      imports: [CommonModule, FormsModule],
      providers: [DxcTextInputService],
      declarations: [FilterOptionsPipe, BoldOptionsPipe],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    fireEvent.click(input);
    expect(screen.getByDisplayValue("Default value"));
    fireEvent.input(input, { target: { value: "new value" } });
    await waitFor(() => {
      expect(screen.getByDisplayValue("new value"));
    });
  });

  test("controlled dxc-input-text input with clear, change and blur", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextInputComponent, {
      componentProperties: {
        label: "test-input",
        clearable: true,
        value: "initial string",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
        optional: true,
      },
      imports: [CommonModule, FormsModule],
      providers: [DxcTextInputService],
      declarations: [FilterOptionsPipe, BoldOptionsPipe],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    fireEvent.click(input);
    expect(screen.getByDisplayValue("initial string"));
    fireEvent.input(input, { target: { value: "new value" } });
    expect(onChange).toHaveBeenCalledWith({ value: "new value", error: undefined });
    await waitFor(() => {
      fireEvent.blur(input);
      expect(onBlur).toHaveBeenCalledWith({
        error: undefined,
        value: "initial string",
      });
      fireEvent.click(screen.getByLabelText("Clear"));
      expect(onChange).toHaveBeenCalledWith({ value: "", error: undefined });
      screen.getByDisplayValue("initial string");
    });
  });

  test("controlled dxc-input-text onError pattern", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextInputComponent, {
      componentProperties: {
        label: "Input label",
        clearable: true,
        value: "initial",
        pattern: ".{10,15}",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
        optional: true,
      },
      imports: [CommonModule, FormsModule],
      providers: [DxcTextInputService],
      declarations: [FilterOptionsPipe, BoldOptionsPipe],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    fireEvent.click(input);
    expect(screen.getByDisplayValue("initial"));
    fireEvent.input(input, { target: { value: "new value" } });
    expect(onChange).toHaveBeenCalledWith({
      value: "new value",
      error: "Please use a valid pattern",
    });
    fireEvent.blur(input);
    await waitFor(() => {
      expect(screen.getByDisplayValue("initial"));
      expect(onBlur).toHaveBeenCalledWith({
        error: "Please use a valid pattern",
        value: "initial",
      });
    });
    fireEvent.click(screen.getByLabelText("Clear"));
    await waitFor(() => {
      expect(onChange).toHaveBeenCalledWith({ value: "", error: undefined });
      expect(screen.getByDisplayValue("initial"));
    });
  });

  test("controlled dxc-input-text onError length", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextInputComponent, {
      componentProperties: {
        label: "Input label",
        value: "initial",
        clearable: true,
        minLength: 2,
        maxLength: 5,
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
        optional: true,
      },
      imports: [CommonModule, FormsModule],
      providers: [DxcTextInputService],
      declarations: [FilterOptionsPipe, BoldOptionsPipe],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    fireEvent.click(input);
    expect(screen.getByDisplayValue("initial"));
    fireEvent.input(input, { target: { value: "new value" } });
    expect(onChange).toHaveBeenCalledWith({
      value: "new value",
      error: "Min length 2, Max length 5",
    });
    fireEvent.blur(input);
    await waitFor(() => {
      expect(screen.getByDisplayValue("initial"));
      expect(onBlur).toHaveBeenCalledWith({
        error: "Min length 2, Max length 5",
        value: "initial",
      });
    });
    fireEvent.click(screen.getByLabelText("Clear"));
    await waitFor(() => {
      expect(onChange).toHaveBeenCalledWith({ value: "", error: undefined });
      expect(screen.getByDisplayValue("initial"));
    });
  });

  test("controlled dxc-input-text input with optional error", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();
    await render(DxcTextInputComponent, {
      componentProperties: {
        label: "test-input",
        clearable: true,
        value: "initial string",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
      },
      imports: [CommonModule, FormsModule],
      providers: [DxcTextInputService],
      declarations: [FilterOptionsPipe, BoldOptionsPipe],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    fireEvent.click(input);
    expect(screen.getByDisplayValue("initial string"));
    fireEvent.input(input, { target: { value: "new value" } });
    expect(onChange).toHaveBeenCalledWith({ value: "new value", error: undefined });
    await waitFor(() => {
      fireEvent.blur(input);
      expect(onBlur).toHaveBeenCalledWith({
        error: undefined,
        value: "initial string",
      });
      fireEvent.click(screen.getByLabelText("Clear"));
      expect(onChange).toHaveBeenCalledWith({
        value: "",
        error: "This field is required. Please, enter a value.",
      });
      screen.getByDisplayValue("initial string");
    });
  });
});
Example #18
Source File: dxc-tabs.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcTabs tests", () => {
  test("should render dxc-tabs", async () => {
    const tabs = await render(
      `<dxc-tabs>
        <dxc-tab label="Tab1"></dxc-tab>
        <dxc-tab label="Tab2"></dxc-tab>
        <dxc-tab label="Tab3"></dxc-tab>
      </dxc-tabs>`,
      {
        componentProperties: {},
        imports: [DxcTabsModule],
        excludeComponentDeclaration: true,
      }
    );
    tabs.detectChanges();
    expect(tabs.getByText("Tab1")).toBeTruthy();
    expect(tabs.getByText("Tab2")).toBeTruthy();
    expect(tabs.getByText("Tab3")).toBeTruthy();
  });

  test("should render dxc-tabs with default value", async () => {
    const clickFunction = jest.fn();
    const tabs = await render(
      `<dxc-tabs margin="xsmall" defaultActiveTabIndex="2">
        <dxc-tab label="Tab1" (onTabClick)="clickFunction($event)"></dxc-tab>
        <dxc-tab label="Tab2" (onTabClick)="clickFunction($event)"></dxc-tab>
        <dxc-tab label="Tab3" (onTabClick)="clickFunction($event)"></dxc-tab>
      </dxc-tabs>`,
      {
        componentProperties: { clickFunction },
        imports: [DxcTabsModule],
        excludeComponentDeclaration: true,
      }
    );
    tabs.detectChanges();
    const arrTabs = screen.getAllByRole("tab");
    expect(arrTabs[0].getAttribute("aria-selected")).toBe("false");
    expect(arrTabs[1].getAttribute("aria-selected")).toBe("false");
    expect(arrTabs[2].getAttribute("aria-selected")).toBe("true");
    expect(tabs.getByText("Tab1")).toBeTruthy();
    expect(tabs.getByText("Tab2")).toBeTruthy();
    expect(tabs.getByText("Tab3")).toBeTruthy();

    const tab1 = screen.getByText("Tab1");
    fireEvent.click(tab1);
    tabs.detectChanges();
    expect(clickFunction).toHaveBeenCalledWith(0);
    expect(arrTabs[0].getAttribute("aria-selected")).toBe("true");
    expect(arrTabs[1].getAttribute("aria-selected")).toBe("false");
    expect(arrTabs[2].getAttribute("aria-selected")).toBe("false");
  });

  test("should render dxc-badge", async () => {
    const tabs = await render(
      `<dxc-tabs>
        <dxc-tab label="Tab1" notificationNumber="90"></dxc-tab>
        <dxc-tab label="Tab2" notificationNumber="150"></dxc-tab>
        <dxc-tab label="Tab3"></dxc-tab>
      </dxc-tabs>`,
      {
        componentProperties: {},
        imports: [DxcTabsModule],
        excludeComponentDeclaration: true,
      }
    );
    tabs.detectChanges();
    expect(tabs.getByText("90")).toBeTruthy();
    expect(tabs.getByText("+99")).toBeTruthy();
  });

  test("should render uncontrolled tabs", async () => {
    const clickFunction = jest.fn();
    const tabs = await render(
      `<dxc-tabs>
        <dxc-tab label="Tab1" (onTabClick)="clickFunction($event)"></dxc-tab>
        <dxc-tab label="Tab2" (onTabClick)="clickFunction($event)"></dxc-tab>
        <dxc-tab label="Tab3" (onTabClick)="clickFunction($event)"></dxc-tab>
      </dxc-tabs>`,
      {
        componentProperties: { clickFunction },
        imports: [DxcTabsModule],
        excludeComponentDeclaration: true,
      }
    );
    tabs.detectChanges();
    const tab1 = screen.getByText("Tab1");
    const tab2 = screen.getByText("Tab2");
    fireEvent.click(tab2);
    tabs.detectChanges();
    expect(clickFunction).toHaveBeenCalledWith(1);
    tabs.detectChanges();
    fireEvent.click(tab1);
    tabs.detectChanges();
    expect(clickFunction).toHaveBeenCalledWith(0);
  });

  test("should render controlled tabs", async () => {
    const clickFunction = jest.fn();
    const tabs = await render(
      `<dxc-tabs [activeTabIndex]="0">
        <dxc-tab label="Tab1" (onTabClick)="clickFunction($event)"></dxc-tab>
        <dxc-tab label="Tab2" (onTabClick)="clickFunction($event)"></dxc-tab>
        <dxc-tab label="Tab3" (onTabClick)="clickFunction($event)"></dxc-tab>
      </dxc-tabs>`,
      {
        componentProperties: { clickFunction },
        imports: [DxcTabsModule],
        excludeComponentDeclaration: true,
      }
    );
    tabs.detectChanges();
    const arrTabs = screen.getAllByRole("tab");
    expect(arrTabs[0].getAttribute("aria-selected")).toBe("true");
    expect(arrTabs[1].getAttribute("aria-selected")).toBe("false");
    expect(arrTabs[2].getAttribute("aria-selected")).toBe("false");
    const tab2 = screen.getByText("Tab2");
    const tab3 = screen.getByText("Tab3");
    fireEvent.click(tab2);
    tabs.detectChanges();
    expect(clickFunction).toHaveBeenCalledWith(1);
    expect(arrTabs[0].getAttribute("aria-selected")).toBe("false");
    expect(arrTabs[1].getAttribute("aria-selected")).toBe("true");
    expect(arrTabs[2].getAttribute("aria-selected")).toBe("false");
    tabs.detectChanges();
    fireEvent.click(tab3);
    tabs.detectChanges();
    expect(clickFunction).toHaveBeenCalledWith(2);
    expect(arrTabs[0].getAttribute("aria-selected")).toBe("false");
    expect(arrTabs[1].getAttribute("aria-selected")).toBe("false");
    expect(arrTabs[2].getAttribute("aria-selected")).toBe("true");
  });
});
Example #19
Source File: dxc-select.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcSelectComponent tests", () => {
  test("should render dxc-select", async () => {
    const dxcSelect = await render(DxcSelectComponent, {
      componentProperties: {
        label: "Select label",
        helperText: "Helper Text",
      },
      excludeComponentDeclaration: true,
      imports: [DxcSelectModule],
    });

    expect(dxcSelect.getByText("Select label"));
    expect(dxcSelect.getByText("Helper Text"));
  });

  test("should render list of options", async () => {
    const array1: Option[] = [
      { label: "label1", value: "1" },
      { label: "label2", value: "2" },
      { label: "label6", value: "6" },
      { label: "label9", value: "9" },
      { label: "aida", value: "10" },
      { label: "pepe", value: "11" },
    ];
    const dxcSelect = await render(DxcSelectComponent, {
      componentProperties: {
        label: "Select label",
        helperText: "Helper Text",
        options: array1,
      },
      excludeComponentDeclaration: true,
      imports: [DxcSelectModule],
    });

    expect(dxcSelect.getByText("Select label"));
    expect(dxcSelect.getByText("Helper Text"));
    fireEvent.click(dxcSelect.getByText("Choose an option"));
    expect(dxcSelect.getByText("label1"));
  });

  test("dxc-select defaultValue functionality", async () => {
    const array1: Option[] = [
      { label: "label1", value: "1" },
      { label: "label2", value: "2" },
      { label: "label6", value: "6" },
      { label: "label9", value: "9" },
      { label: "aida", value: "10" },
      { label: "pepe", value: "11" },
    ];
    const changeMock = jest.fn((x) => {});
    const dxcSelect = await render(DxcSelectComponent, {
      componentProperties: {
        label: "Select label",
        helperText: "Helper Text",
        options: array1,
        onChange: {
          emit: changeMock,
        } as any,
        defaultValue: "1",
      },
      imports: [DxcSelectModule],
      excludeComponentDeclaration: true,
    });
    expect(dxcSelect.getByText("Select label"));
    expect(dxcSelect.getByText("Helper Text"));
    expect(dxcSelect.getByText("label1"));
    fireEvent.click(dxcSelect.getByRole("combobox"));
    expect(screen.getAllByText("label1")[1].getAttribute("aria-selected")).toBe(
      "true"
    );
    fireEvent.click(screen.getByText("aida"));
    expect(changeMock).toHaveBeenCalledWith({ value: "10", error: undefined });
    fireEvent.click(dxcSelect.getByRole("combobox"));
    expect(dxcSelect.getByText("aida"));
  });

  test("dxc-select single controlled functionality", async () => {
    const array1: Option[] = [
      { label: "label1", value: "1" },
      { label: "label2", value: "2" },
      { label: "label6", value: "6" },
      { label: "label9", value: "9" },
      { label: "aida", value: "10" },
      { label: "pepe", value: "11" },
    ];
    const changeMock = jest.fn((x) => {});
    const dxcSelect = await render(DxcSelectComponent, {
      componentProperties: {
        label: "Select label",
        helperText: "Helper Text",
        options: array1,
        onChange: {
          emit: changeMock,
        } as any,
        value: "1",
      },
      imports: [DxcSelectModule],
      excludeComponentDeclaration: true,
    });
    expect(dxcSelect.getByText("Select label"));
    expect(dxcSelect.getByText("Helper Text"));
    expect(dxcSelect.getByText("label1"));
    fireEvent.click(dxcSelect.getByRole("combobox"));
    expect(screen.getAllByText("label1")[1].getAttribute("aria-selected")).toBe(
      "true"
    );
    fireEvent.click(screen.getByText("aida"));
    expect(changeMock).toHaveBeenCalledWith({ value: "10", error: undefined });
    expect(screen.getAllByText("label1")[1].getAttribute("aria-selected")).toBe(
      "true"
    );
    expect(screen.getAllByText("aida")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("label2")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("label6")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("label9")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("pepe")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
  });

  test("dxc-select single uncontrolled functionality", async () => {
    const array1: Option[] = [
      { label: "label1", value: "1" },
      { label: "label2", value: "2" },
      { label: "label6", value: "6" },
      { label: "label9", value: "9" },
      { label: "aida", value: "10" },
      { label: "pepe", value: "11" },
    ];
    const changeMock = jest.fn((x) => {});
    const dxcSelect = await render(DxcSelectComponent, {
      componentProperties: {
        label: "Select label",
        helperText: "Helper Text",
        options: array1,
        onChange: {
          emit: changeMock,
        } as any,
      },
      imports: [DxcSelectModule],
      excludeComponentDeclaration: true,
    });
    expect(dxcSelect.getByText("Select label"));
    expect(dxcSelect.getByText("Helper Text"));
    dxcSelect.getByText("Choose an option");
    fireEvent.click(dxcSelect.getByRole("combobox"));
    fireEvent.click(screen.getByText("aida"));
    expect(changeMock).toHaveBeenCalledWith({ value: "10", error: undefined });
    expect(screen.getAllByText("aida")[1].getAttribute("aria-selected")).toBe(
      "true"
    );
    expect(screen.getAllByText("label1")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("label2")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("label6")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("label9")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("pepe")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    fireEvent.click(screen.getByText("pepe"));
    expect(changeMock).toHaveBeenCalledWith({ value: "11", error: undefined });
    expect(screen.getAllByText("pepe")[1].getAttribute("aria-selected")).toBe(
      "true"
    );
    expect(screen.getAllByText("label1")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("label2")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("label6")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("label9")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
    expect(screen.getAllByText("aida")[0].getAttribute("aria-selected")).toBe(
      "false"
    );
  });

  test("should render optional error", async () => {
    const array1: Option[] = [
      { label: "label1", value: "1" },
      { label: "label2", value: "2" },
      { label: "label6", value: "6" },
      { label: "label9", value: "9" },
      { label: "aida", value: "10" },
      { label: "pepe", value: "11" },
    ];
    const onBlur = jest.fn((x) => {});
    const dxcSelect = await render(DxcSelectComponent, {
      componentProperties: {
        label: "Select label",
        helperText: "Helper Text",
        options: array1,
        onBlur: {
          emit: onBlur,
        } as any,
      },
      excludeComponentDeclaration: true,
      imports: [DxcSelectModule],
    });

    expect(dxcSelect.getByText("Select label"));
    expect(dxcSelect.getByText("Helper Text"));
    fireEvent.click(dxcSelect.getByText("Choose an option"));
    fireEvent.focusOut(dxcSelect.getByText("Choose an option"));
    expect(onBlur).toHaveBeenCalledWith({
      value: "",
      error: "This field is required. Please, enter a value.",
    });
  });
});
Example #20
Source File: dxc-password-input.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcPasswordInputComponent", () => {
  test("should render dxc-password", async () => {
    await render(DxcPasswordInputComponent, {
      componentProperties: {
        label: "test-input",
        helperText: "helper-text",
      },
      imports: [DxcTextInputModule],
    });

    expect(screen.queryByText("test-input")).toBeInTheDocument();
    expect(screen.queryByText("helper-text")).toBeInTheDocument();
  });

  test("should clear input password", async () => {
    const onChange = jest.fn();
    await render(DxcPasswordInputComponent, {
      componentProperties: {
        label: "test-input",
        helperText: "helper-text",
        value: "password-test",
        clearable: true,
        onChange: {
          emit: onChange,
        } as any,
      },
      imports: [DxcTextInputModule],
    });

    const btn = screen.getByLabelText("Clear");

    expect(screen.queryByText("test-input")).toBeInTheDocument();
    expect(screen.getByDisplayValue("password-test")).toBeTruthy();
    fireEvent.click(btn);
    expect(onChange).toHaveBeenCalledWith({
      value: "",
      error: "This field is required. Please, enter a value.",
    });
  });

  test("should render defaultValue", async () => {
    const onChange = jest.fn();
    await render(DxcPasswordInputComponent, {
      componentProperties: {
        label: "test-input",
        helperText: "helper-text",
        defaultValue: "default",
        clearable: true,
        onChange: {
          emit: onChange,
        } as any,
      },
      imports: [DxcTextInputModule],
    });

    const btn = screen.getByLabelText("Clear");

    expect(screen.queryByText("test-input")).toBeInTheDocument();
    expect(screen.getByDisplayValue("default")).toBeTruthy();
    fireEvent.click(btn);
    expect(onChange).toHaveBeenCalledWith({
      value: "",
      error: "This field is required. Please, enter a value.",
    });
  });

  test("should mask input password", async () => {
    const onChange = jest.fn();
    await render(DxcPasswordInputComponent, {
      componentProperties: {
        label: "test-input",
        helperText: "helper-text",
        value: "password-test",
        onChange: {
          emit: onChange,
        } as any,
      },
      imports: [DxcTextInputModule],
    });
    const input = <HTMLInputElement>screen.getByRole("textbox");
    const btn = screen.getByLabelText("Action");

    expect(screen.getByDisplayValue("password-test")).toBeTruthy();
    expect(input.type).toBe("password");
    fireEvent.click(btn);
    expect(input.type).toBe("text");
    fireEvent.click(btn);
    expect(input.type).toBe("password");
  });

  test("controlled dxc-password error pattern", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();

    await render(DxcPasswordInputComponent, {
      componentProperties: {
        label: "test-input",
        clearable: true,
        value: "initial",
        pattern: ".{10,15}",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
      },
      imports: [DxcTextInputModule],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    expect(input).toHaveFocus();
    expect(screen.getByDisplayValue("initial"));
    fireEvent.input(input, { target: { value: "new value" } });
    expect(onChange).toHaveBeenCalledWith({
      value: "new value",
      error: "Please use a valid pattern",
    });
    expect(screen.getByDisplayValue("initial"));
    fireEvent.blur(input);
    expect(onBlur).toHaveBeenCalledWith({
      error: "Please use a valid pattern",
      value: "initial",
    });
  });

  test("controlled dxc-password onError length", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();

    await render(DxcPasswordInputComponent, {
      componentProperties: {
        label: "test-input",
        clearable: true,
        value: "initial",
        minLength: 2,
        maxLength: 5,
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
      },
      imports: [DxcTextInputModule],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    expect(input).toHaveFocus();
    expect(screen.getByDisplayValue("initial"));
    fireEvent.input(input, { target: { value: "new value" } });
    expect(onChange).toHaveBeenCalledWith({
      value: "new value",
      error: "Min length 2, Max length 5",
    });
    expect(screen.getByDisplayValue("initial"));
    fireEvent.blur(input);
    expect(onBlur).toHaveBeenCalledWith({
      error: "Min length 2, Max length 5",
      value: "initial",
    });
  });
});
Example #21
Source File: dxc-paginator.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcPaginator tests", () => {
  test("should render default dxc-paginator", async () => {
    const paginator = await render(DxcPaginatorComponent, {
      componentProperties: {},
      imports: [DxcPaginatorModule],
      excludeComponentDeclaration: true,
    });
    expect(paginator.getByText("1 to 1 of 1")).toBeTruthy();
    expect(paginator.getByText("Page: 1 of 1")).toBeTruthy();
  });

  test("Paginator renders with itemsPerPage", async () => {
    const perPage = 10;
    const total = 20;
    const current = 1;
    const paginator = await render(DxcPaginatorComponent, {
      componentProperties: {
        itemsPerPage: perPage,
        totalItems: total,
        currentPage: current,
      },
      imports: [DxcPaginatorModule],
      excludeComponentDeclaration: true,
    });
    expect(paginator.getByText("Page: 1 of 2")).toBeTruthy();
    expect(paginator.getByText("1 to 10 of 20")).toBeTruthy();
  });

  test("Paginator renders with totalItems", async () => {
    const total = 20;
    const paginator = await render(DxcPaginatorComponent, {
      componentProperties: {
        totalItems: total,
      },
      imports: [DxcPaginatorModule],
      excludeComponentDeclaration: true,
    });
    expect(paginator.getByText("1 to 5 of 20")).toBeTruthy();
    expect(paginator.getByText("Page: 1 of 4")).toBeTruthy();
  });

  test("Paginator renders with correct text in second page", async () => {
    const paginationActions: Array<string> = ["prev", "next", "first"];
    const page: number = 2;
    const totalItems: number = 27;
    const itemsPerPage: number = 10;

    const paginator = await render(DxcPaginatorComponent, {
      componentProperties: {
        itemsPerPage: itemsPerPage,
        totalItems: totalItems,
        currentPage: page,
      },
      imports: [DxcPaginatorModule],
      excludeComponentDeclaration: true,
    });
    expect(paginator.getByText("11 to 20 of 27")).toBeTruthy();
    expect(paginator.getByText("Page: 2 of 3")).toBeTruthy();
  });

  test("should click next function", async () => {
    const navegateFunction = jest.fn();
    const page: number = 1;
    const totalItems: number = 27;
    const itemsPerPage: number = 10;
    const paginator = await render(
      `<dxc-paginator (onGoToPage)="navegateFunction($event,'next')" [itemsPerPage]=${itemsPerPage} [totalItems]=${totalItems} [currentPage]=${page} [paginationActions]="['next']" ></dxc-paginator>`,
      {
        componentProperties: {
          navegateFunction,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    expect(paginator.getByText("1 to 10 of 27")).toBeTruthy();
    const nextButton = paginator.getAllByRole("button");
    fireEvent.click(nextButton[0]);
    expect(navegateFunction).toHaveBeenCalled();
  });

  test("should click prev function", async () => {
    const navegateFunction = jest.fn();
    const page: number = 2;
    const totalItems: number = 20;
    const itemsPerPage: number = 10;
    const paginator = await render(
      `<dxc-paginator (onGoToPage)="navegateFunction($event,'prev')" [itemsPerPage]=${itemsPerPage} [totalItems]=${totalItems} [currentPage]=${page} [paginationActions]="['prev']" ></dxc-paginator>`,
      {
        componentProperties: {
          navegateFunction,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    const btn = paginator.getAllByRole("button");
    fireEvent.click(btn[0]);
    expect(navegateFunction).toHaveBeenCalled();
  });

  test("should click first function", async () => {
    const navegateFunction = jest.fn();
    const page: number = 2;
    const totalItems: number = 30;
    const itemsPerPage: number = 10;
    const paginator = await render(
      `<dxc-paginator (onGoToPage)="navegateFunction($event,'first')" [itemsPerPage]=${itemsPerPage} [totalItems]=${totalItems} [currentPage]=${page} [paginationActions]="['first']" ></dxc-paginator>`,
      {
        componentProperties: {
          navegateFunction,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    const btn = paginator.getAllByRole("button");
    fireEvent.click(btn[0]);
    expect(navegateFunction).toHaveBeenCalled();
  });

  test("should click last function", async () => {
    const navegateFunction = jest.fn();
    const page: number = 1;
    const totalItems: number = 20;
    const itemsPerPage: number = 10;
    const paginator = await render(
      `<dxc-paginator (onGoToPage)="navegateFunction($event,'last')" [itemsPerPage]=${itemsPerPage} [totalItems]=${totalItems} [currentPage]=${page} [paginationActions]="['last']" ></dxc-paginator>`,
      {
        componentProperties: {
          navegateFunction,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    const btn = paginator.getAllByRole("button");
    fireEvent.click(btn[0]);
    expect(navegateFunction).toHaveBeenCalled();
  });

  test("should click disabled next function", async () => {
    const navegateFunction = jest.fn();
    const page: number = 2;
    const totalItems: number = 20;
    const itemsPerPage: number = 10;
    const paginator = await render(
      `<dxc-paginator (onGoToPage)="navegateFunction($event,'next')" [itemsPerPage]=${itemsPerPage} [totalItems]=${totalItems} [currentPage]=${page} [paginationActions]="['next']" ></dxc-paginator>`,
      {
        componentProperties: {
          navegateFunction,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    const nextButton = paginator.getAllByRole("button");
    expect(nextButton[0].hasAttribute("disabled")).toBe(true);
  });

  test("should click disabled prev function", async () => {
    const navegateFunction = jest.fn();
    const page: number = 1;
    const totalItems: number = 20;
    const itemsPerPage: number = 10;
    const paginator = await render(
      `<dxc-paginator (onGoToPage)="navegateFunction($event,'prev')" [itemsPerPage]=${itemsPerPage} [totalItems]=${totalItems} [currentPage]=${page} [paginationActions]="['prev']" ></dxc-paginator>`,
      {
        componentProperties: {
          navegateFunction,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    const btn = paginator.getAllByRole("button");
    expect(btn[0].hasAttribute("disabled")).toBe(true);
  });

  test("should click disabled first function", async () => {
    const navegateFunction = jest.fn();
    const page: number = 1;
    const totalItems: number = 20;
    const itemsPerPage: number = 10;
    const paginator = await render(
      `<dxc-paginator (onGoToPage)="navegateFunction($event,'first')" [itemsPerPage]=${itemsPerPage} [totalItems]=${totalItems} [currentPage]=${page} [paginationActions]="['first']" ></dxc-paginator>`,
      {
        componentProperties: {
          navegateFunction,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    const btn = paginator.getAllByRole("button");
    expect(btn[0].hasAttribute("disabled")).toBe(true);
  });

  test("should click last function", async () => {
    const navegateFunction = jest.fn();
    const page: number = 2;
    const totalItems: number = 20;
    const itemsPerPage: number = 10;
    const paginator = await render(
      `<dxc-paginator (onGoToPage)="navegateFunction($event,'last')" [itemsPerPage]=${itemsPerPage} [totalItems]=${totalItems} [currentPage]=${page} [paginationActions]="['last']" ></dxc-paginator>`,
      {
        componentProperties: {
          navegateFunction,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    const btn = paginator.getAllByRole("button");
    expect(btn[0].hasAttribute("disabled")).toBe(true);
  });

  test("should disable last and next buttons", async () => {
    const navegateFunction = jest.fn();
    const page: number = 2;
    const totalItems: number = 20;
    const itemsPerPage: number = 10;
    const paginator = await render(
      `<dxc-paginator (onGoToPage)="navegateFunction($event,'next')" (lastFunction)="navegateFunction($event,'last')" 
    (firstFunction)="navegateFunction($event,'first')" (prevFunction)="navegateFunction($event,'prev')" 
    [itemsPerPage]=${itemsPerPage} [totalItems]=${totalItems} [currentPage]=${page} ></dxc-paginator>`,
      {
        componentProperties: {
          navegateFunction,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    const firstButton = paginator.getAllByRole("button")[0];
    const prevButton = paginator.getAllByRole("button")[1];
    const nextButton = paginator.getAllByRole("button")[2];
    const lastButton = paginator.getAllByRole("button")[3];
    expect(firstButton.hasAttribute("disabled")).toBeFalsy();
    expect(prevButton.hasAttribute("disabled")).toBeFalsy();
    expect(nextButton.hasAttribute("disabled")).toBeTruthy();
    expect(lastButton.hasAttribute("disabled")).toBeTruthy();
  });

  test("should disable first and previous buttons", async () => {
    const navegateFunction = jest.fn();
    const page: number = 1;
    const totalItems: number = 20;
    const itemsPerPage: number = 10;
    const paginator = await render(
      `<dxc-paginator (onGoToPage)="navegateFunction($event,'next')" (lastFunction)="navegateFunction($event,'last')" 
    (firstFunction)="navegateFunction($event,'first')" (prevFunction)="navegateFunction($event,'prev')" 
    [itemsPerPage]=${itemsPerPage} [totalItems]=${totalItems} [currentPage]=${page} ></dxc-paginator>`,
      {
        componentProperties: {
          navegateFunction,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    const firstButton = paginator.getAllByRole("button")[0];
    const prevButton = paginator.getAllByRole("button")[1];
    const nextButton = paginator.getAllByRole("button")[2];
    const lastButton = paginator.getAllByRole("button")[3];
    expect(firstButton.hasAttribute("disabled")).toBeTruthy();
    expect(prevButton.hasAttribute("disabled")).toBeTruthy();
    expect(nextButton.hasAttribute("disabled")).toBeFalsy();
    expect(lastButton.hasAttribute("disabled")).toBeFalsy();
  });

  test("Paginator renders with items per page options", async () => {
    const itemsPerPageOptions = [10, 20];

    const paginator = await render(
      `<dxc-paginator itemsPerPage="10" [itemsPerPageOptions]="itemsPerPageOptions" totalItems="27" currentPage="2"></dxc-paginator>`,
      {
        componentProperties: { itemsPerPageOptions: itemsPerPageOptions },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    expect(screen.getByText("Items per page")).toBeTruthy();
    expect(screen.getByRole("combobox")).toBeTruthy();
  });

  test("Paginator change items per page value", async () => {
    const changeMock = jest.fn();
    const itemsPerPageOptions = [10, 20];

    const paginator = await render(
      `<dxc-paginator itemsPerPage="10" [itemsPerPageOptions]="itemsPerPageOptions" totalItems="27" (itemsPerPageFunction)="changeMock($event)" currentPage="2"></dxc-paginator>`,
      {
        componentProperties: {
          itemsPerPageOptions,
          changeMock,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );
    expect(screen.getByText("Items per page")).toBeTruthy();
    fireEvent.click(paginator.getByRole("combobox"));
    paginator.detectChanges();
    fireEvent.click(screen.getByText("20"));
    expect(changeMock).toHaveBeenCalledWith(20);
  });

  test("Paginator renders with go to page options", async () => {
    const changeMock = jest.fn();
    const itemsPerPageOptions = [10, 20];

    const paginator = await render(
      `<dxc-paginator showGoToPage="true" itemsPerPage="10" totalItems="27" (onGoToPage)="changeMock($event)" currentPage="2"></dxc-paginator>`,
      {
        componentProperties: {
          itemsPerPageOptions,
          changeMock,
        },
        imports: [DxcPaginatorModule],
        excludeComponentDeclaration: true,
      }
    );

    expect(screen.getByText("Go to page")).toBeTruthy();
    fireEvent.click(paginator.getByRole("combobox"));
    paginator.detectChanges();
    fireEvent.click(screen.getByText("3"));
    expect(changeMock).toHaveBeenCalledWith(3);
  });
});
Example #22
Source File: dxc-input-text.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcTextInputComponent autocomplete tests", () => {
  test("should render autocomplete options", async () => {
    const dxcInput = await render(DxcInputTextComponent, {
      componentProperties: {
        label: "test-input",
        assistiveText: "assistive text",
        autocompleteOptions: ["One", "Two", "Three"],
      },
      imports: [
        MatInputModule,
        MatAutocompleteModule,
        FormsModule,
        ReactiveFormsModule,
      ],
    });

    expect(dxcInput.getByText("test-input"));
    expect(dxcInput.getByText("assistive text"));
    fireEvent.focusIn(dxcInput.getByRole("combobox"));
    dxcInput.detectChanges();
    expect(screen.getByText("One"));
    expect(screen.getByText("Two"));
    expect(screen.getByText("Three"));
  });

  test("should filter autocomplete options", async () => {
    const dxcInput = await render(DxcInputTextComponent, {
      componentProperties: {
        label: "test-input",
        assistiveText: "assistive text",
        autocompleteOptions: ["One", "Two", "Three"],
      },
      imports: [
        MatInputModule,
        MatAutocompleteModule,
        FormsModule,
        ReactiveFormsModule,
      ],
    });

    expect(dxcInput.getByText("test-input"));
    expect(dxcInput.getByText("assistive text"));
    const input = <HTMLInputElement>dxcInput.getByRole("combobox");
    fireEvent.input(input, { target: { value: "O" } });
    fireEvent.focusIn(dxcInput.getByRole("combobox"));
    dxcInput.detectChanges();
    expect(screen.getByText("One"));
    expect(screen.getByText("Two"));
    const filteredOutOption = screen.queryByText("Three");
    expect(filteredOutOption).toBeNull();
  });

  test("should use autocomplete function", async () => {
    const autocompleteFunction = jest.fn(() => {
      return of(["One", "Two", "Three"]);
    });
    const dxcInput = await render(DxcInputTextComponent, {
      componentProperties: {
        label: "test-input",
        assistiveText: "assistive text",
        autocompleteOptions: autocompleteFunction,
      },
      imports: [
        MatInputModule,
        MatAutocompleteModule,
        FormsModule,
        ReactiveFormsModule,
      ],
    });

    expect(dxcInput.getByText("test-input"));
    expect(dxcInput.getByText("assistive text"));
    fireEvent.focusIn(dxcInput.getByRole("combobox"));
    dxcInput.detectChanges();
    expect(screen.getByText("One"));
    expect(screen.getByText("Two"));
    expect(screen.getByText("Three"));
  });

  test("should use autocomplete function returning an observable", async () => {
    const autocompleteFunction = jest.fn(() => {
      return of(["One", "Two", "Three"]).pipe(
        switchMap((options) => of(options).pipe(delay(1000)))
      );
    });
    const dxcInput = await render(DxcInputTextComponent, {
      componentProperties: {
        label: "test-input",
        assistiveText: "assistive text",
        autocompleteOptions: autocompleteFunction,
      },
      imports: [
        MatInputModule,
        MatAutocompleteModule,
        FormsModule,
        ReactiveFormsModule,
      ],
    });

    expect(dxcInput.getByText("test-input"));
    expect(dxcInput.getByText("assistive text"));
    fireEvent.focusIn(dxcInput.getByRole("combobox"));
    dxcInput.detectChanges();
    expect(screen.getByText("Searching..."));
    await waitFor(
      () => {
        dxcInput.detectChanges();
        expect(screen.getByText("Two")).toBeTruthy();
      },
      { timeout: 1200 }
    );
  });
});
Example #23
Source File: dxc-file-input.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcFileInputComponent", () => {
  test("should render dxc-file-input in file mode", async () => {
    const fileInput = await render(DxcFileInputComponent, {
      componentProperties: {
        label: "Label",
        helperText: "Helper Text",
      },
      excludeComponentDeclaration: true,
      imports: [DxcFileInputModule],
    });

    expect(fileInput.getByText("Select files"));
    expect(fileInput.getByText("Label"));
    expect(fileInput.getByText("Helper Text"));
  });

  test("should render dxc-file-input with custom buttonLabel", async () => {
    const fileInput = await render(DxcFileInputComponent, {
      componentProperties: {
        label: "Label",
        helperText: "Helper Text",
        buttonLabel: "Custom Button Label",
      },
      excludeComponentDeclaration: true,
      imports: [DxcFileInputModule],
    });

    expect(fileInput.getByText("Custom Button Label"));
    expect(fileInput.getByText("Label"));
    expect(fileInput.getByText("Helper Text"));
  });


  test("should render dxc-file-input in file drop mode", async () => {
    const fileInput = await render(DxcFileInputComponent, {
      componentProperties: {
        mode: "filedrop",
      },
      excludeComponentDeclaration: true,
      imports: [DxcFileInputModule],
    });

    expect(fileInput.getByText("or drop files"));
  });

  test("should render dxc-file-input in drop zone mode", async () => {
    const fileInput = await render(DxcFileInputComponent, {
      componentProperties: {
        mode: "dropzone",
      },
      excludeComponentDeclaration: true,
      imports: [DxcFileInputModule],
    });

    expect(fileInput.getByText("or drop files"));
  });

  test("should render disabled dxc-file-input", async () => {
    const fileInput = await render(DxcFileInputComponent, {
      componentProperties: {
        disabled: true,
      },
      excludeComponentDeclaration: true,
      imports: [DxcFileInputModule],
    });

    expect(fileInput.getByText("Select files"));
    const btn = fileInput.getAllByRole("button");
    expect(btn[0].hasAttribute("disabled")).toBe(true);
  });

  test("should not have files even if they are selected", async () => {
    const fileInput = await render(
      `<dxc-file-input multiple="false"></dxc-file-input>`,
      {
        excludeComponentDeclaration: true,
        imports: [DxcFileInputModule],
        declarations: [DxcFileInputComponent],
      }
    );
    const inputEl = fileInput.getByTestId("input");
    const file = new File(["foo"], "foo.txt", {
      type: "text/plain",
    });
    fireEvent.change(inputEl, { target: { files: [file] } });
    const fileInScreen = screen.queryByText("foo.txt");
    expect(fileInScreen).toBeFalsy();
  });

  test("should render error when file does not meet minSize", async () => {
    const file = new File(["foo"], "foo.txt", {
      type: "text/plain",
    });
    const value: Array<FileData> = [
      {
        data: file,
        image: "",
        error: "",
      },
    ];
    const callback = jest.fn();
    const fileInput = await render(
      `<dxc-file-input [value]="value" (callbackFile)="callback($event)" [minSize]="50" multiple="false"></dxc-file-input>`,
      {
        componentProperties: { callback, value },
        excludeComponentDeclaration: true,
        imports: [DxcFileInputModule],
        declarations: [DxcFileInputComponent],
      }
    );
    await waitFor(() => {
      fileInput.detectChanges();
      expect(screen.getByText("foo.txt"));
      expect(screen.getByText("File size must be greater than min size."));
    });
  });

  test("should render error when file does not meet maxSize", async () => {
    const file = new File(["foo"], "foo.txt", {
      type: "text/plain",
    });
    const value: Array<FileData> = [
      {
        data: file,
        image: "",
        error: "",
      },
    ];
    const maxSize = 1;
    const callback = jest.fn();
    const fileInput = await render(
      `<dxc-file-input [value]="value" (callbackFile)="callback($event)" [maxSize]="maxSize" multiple="false"></dxc-file-input>`,
      {
        componentProperties: { callback, value, maxSize },
        excludeComponentDeclaration: true,
        imports: [DxcFileInputModule],
        declarations: [DxcFileInputComponent],
      }
    );
    fileInput.detectChanges();
    await waitFor(() => {
      fileInput.detectChanges();
      expect(screen.getByText("foo.txt"));
      expect(screen.getByText("File size must be less than max size."));
    });
  });

  test("render given values when multiple is false", async () => {
    const callback = jest.fn();
    const file = new File(["foo"], "foo.txt", {
      type: "text/plain",
    });
    const file2 = new File(["chucknorris"], "chucknorris.txt", {
      type: "text/plain",
    });
    let value: Array<FileData> = [
      {
        data: file,
        image: "",
        error: "Error for file",
      },
      {
        data: file2,
        image: "",
        error: "Error for file2",
      },
    ];
    const fileInput = await render(DxcFileInputComponent, {
      componentProperties: {
        multiple: false,
        value: value,
        callbackFile: {
          emit: callback,
        } as any,
      },
      excludeComponentDeclaration: true,
      imports: [DxcFileInputModule],
    });

    await waitFor(() => {
      expect(screen.getByText("foo.txt"));
      expect(screen.getByText("chucknorris.txt"));
      expect(screen.getByText("Error for file"));
      expect(screen.getByText("Error for file2"));
    });
  });

  test("render dxc-file-input with multiple files", async () => {
    const callback = jest.fn();
    const file = new File(["foo"], "foo.txt", {
      type: "text/plain",
    });
    const file2 = new File(["test"], "test.txt", {
      type: "text/plain",
    });
    const value = [
      {
        data: file,
        image: "",
      },
      {
        data: file2,
        image: "",
      },
    ];
    const fileInput = await render(
      `<dxc-file-input [value]="value" (callbackFile)="callback($event)"></dxc-file-input>`,
      {
        componentProperties: { callback, value },
        excludeComponentDeclaration: true,
        imports: [DxcFileInputModule],
        declarations: [DxcFileInputComponent],
      }
    );
    const inputEl = fileInput.getByTestId("input");
    await waitFor(() => {
      expect(screen.getByText("foo.txt"));
      expect(screen.getByText("test.txt"));
    });
  });

  test("should remove file from dxc-file-input", async () => {
    const callback = jest.fn();
    const file = new File(["foo"], "foo.txt", {
      type: "text/plain",
    });
    const file2 = new File(["test"], "test.txt", {
      type: "text/plain",
    });
    const value = [
      {
        data: file,
        image: null,
      },
      {
        data: file2,
        image: null,
      },
    ];
    const fileInput = await render(
      `<dxc-file-input [value]="value" (callbackFile)="callback($event)"></dxc-file-input>`,
      {
        componentProperties: { callback, value },
        excludeComponentDeclaration: true,
        imports: [DxcFileInputModule],
        declarations: [DxcFileInputComponent],
      }
    );
    const inputEl = fileInput.getByTestId("input");

    fireEvent.change(inputEl, { target: { files: [file, file2] } });
    fileInput.detectChanges();
    await waitFor(() => {
      expect(screen.getByText("foo.txt"));
    });
    const removeIcons = fileInput.getAllByTestId("removeIcon");
    fireEvent.click(removeIcons[0]);
    await waitFor(() => {
      expect(callback).toHaveBeenCalledWith([
        { data: file2, error: null, image: null },
      ]);
    });
  });

  test("should return callback files", async () => {
    const callback = jest.fn();
    const value = [];
    const fileInput = await render(
      `<dxc-file-input [value]="value" (callbackFile)="callback($event)"></dxc-file-input>`,
      {
        componentProperties: { callback, value },
        excludeComponentDeclaration: true,
        imports: [DxcFileInputModule],
        declarations: [DxcFileInputComponent],
      }
    );
    const inputEl = fileInput.getByTestId("input");
    const file = new File(["foo"], "foo.txt", {
      type: "text/plain",
    });
    const file2 = new File(["(⌐□_□)"], "chucknorris.txt", {
      type: "text/plain",
    });
    fireEvent.change(inputEl, { target: { files: [file, file2] } });
    await waitFor(() => {
      expect(callback).toHaveBeenCalledWith([
        { data: file, error: null, image: null },
        { data: file2, error: null, image: null },
      ]);
    });
  });
});
Example #24
Source File: dxc-date-input.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcDate", () => {
  const newMockDate = new Date("1995/12/03");
  const newValue = "03-12-1995";

  test("should render dxc-date", async () => {
    const { getByText } = await render(DxcDateInputComponent, {
      componentProperties: { label: "test-date" },
      imports: [
        MatDayjsDateModule,
        MatNativeDateModule,
        MatInputModule,
        MatDatepickerModule,
        MdePopoverModule,
        DxcBoxModule,
        CommonModule,
        DxcTextInputModule,
      ],
      providers: [
        { provide: MAT_DATE_FORMATS, useValue: DAYJS_DATE_FORMATS },
        {
          provide: DateAdapter,
          useClass: DayjsDateAdapter,
          deps: [MAT_DATE_LOCALE, Platform],
        },
      ],
    });

    expect(getByText("test-date"));
  });

  test("The input´s value is the same as the one received as a parameter", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();

    await render(DxcDateInputComponent, {
      componentProperties: {
        label: "test-input",
        value: "03-12-1995",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
      },
      imports: [
        MatDayjsDateModule,
        MatNativeDateModule,
        MatInputModule,
        MatDatepickerModule,
        MdePopoverModule,
        DxcBoxModule,
        CommonModule,
        DxcTextInputModule,
      ],
      providers: [
        { provide: MAT_DATE_FORMATS, useValue: DAYJS_DATE_FORMATS },
        {
          provide: DateAdapter,
          useClass: DayjsDateAdapter,
          deps: [MAT_DATE_LOCALE, Platform],
        },
      ],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    const calendarIcon = screen.getByRole("calendarIcon");

    input.focus();
    expect(screen.getByDisplayValue("03-12-1995"));
    fireEvent.click(calendarIcon);
    expect(screen.getByText("DECEMBER 1995"));
    expect(
      screen.getByText("3").classList.contains("mat-calendar-body-selected")
    ).toBeTruthy();
  });

  test("dxc-date value change and default format", async () => {
    const onChange = jest.fn();

    await render(DxcDateInputComponent, {
      componentProperties: {
        label: "test-input",
        onChange: {
          emit: onChange,
        } as any,
      },
      imports: [
        MatDayjsDateModule,
        MatNativeDateModule,
        MatInputModule,
        MatDatepickerModule,
        MdePopoverModule,
        DxcBoxModule,
        CommonModule,
        DxcTextInputModule,
      ],
      providers: [
        { provide: MAT_DATE_FORMATS, useValue: DAYJS_DATE_FORMATS },
        {
          provide: DateAdapter,
          useClass: DayjsDateAdapter,
          deps: [MAT_DATE_LOCALE, Platform],
        },
      ],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    fireEvent.input(input, { target: { value: newValue } });
    expect(onChange).toHaveBeenCalledWith({
      value: newValue,
      error: undefined,
      date: newMockDate,
    });
    expect(screen.getByDisplayValue(newValue));
  });

  test("dxc-date change value twice as uncontrolled", async () => {
    const onChange = jest.fn();

    await render(DxcDateInputComponent, {
      componentProperties: {
        label: "test-input",
        defaultValue: "22-10-1998",
        onChange: {
          emit: onChange,
        } as any,
      },
      imports: [
        MatDayjsDateModule,
        MatNativeDateModule,
        MatInputModule,
        MatDatepickerModule,
        MdePopoverModule,
        DxcBoxModule,
        CommonModule,
        DxcTextInputModule,
      ],
      providers: [
        { provide: MAT_DATE_FORMATS, useValue: DAYJS_DATE_FORMATS },
        {
          provide: DateAdapter,
          useClass: DayjsDateAdapter,
          deps: [MAT_DATE_LOCALE, Platform],
        },
      ],
    });
    expect(screen.getByDisplayValue("22-10-1998"));
    const input = <HTMLInputElement>screen.getByRole("textbox");
    input.focus();
    fireEvent.input(input, { target: { value: newValue } });
    expect(onChange).toHaveBeenCalledWith({
      value: newValue,
      error: undefined,
      date: newMockDate,
    });
    expect(screen.getByDisplayValue(newValue));

    input.focus();
    fireEvent.input(input, { target: { value: "04-10-1996" } });
    expect(onChange).toHaveBeenCalledWith({
      value: "04-10-1996",
      error: undefined,
      date: new Date("1996/10/04"),
    });
    expect(screen.getByDisplayValue("04-10-1996"));
  });

  test("Calendar´s value is the same as the input´s date if it´s right (Depending on the format)", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();

    await render(DxcDateInputComponent, {
      componentProperties: {
        label: "test-input",
        format: "YYYY/MM/DD",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
      },
      imports: [
        MatDayjsDateModule,
        MatNativeDateModule,
        MatInputModule,
        MatDatepickerModule,
        MdePopoverModule,
        DxcBoxModule,
        CommonModule,
        DxcTextInputModule,
      ],
      providers: [
        { provide: MAT_DATE_FORMATS, useValue: DAYJS_DATE_FORMATS },
        {
          provide: DateAdapter,
          useClass: DayjsDateAdapter,
          deps: [MAT_DATE_LOCALE, Platform],
        },
      ],
    });

    const input = <HTMLInputElement>screen.getByRole("textbox");
    const calendarIcon = screen.getByRole("calendarIcon");

    input.focus();
    fireEvent.input(input, { target: { value: "1995/12/03" } });
    expect(onChange).toHaveBeenCalledWith({
      value: "1995/12/03",
      error: undefined,
      date: newMockDate,
    });
    input.focus();
    expect(screen.getByDisplayValue("1995/12/03"));
    fireEvent.click(calendarIcon);
    waitFor(() => {
      expect(screen.getByText("DECEMBER 1995"));
    });
    waitFor(() => {
      expect(
        screen.getByText("3").classList.contains("mat-calendar-body-selected")
      ).toBeTruthy();
    });
  });

  test("dxc-date invalid value", async () => {
    const onChange = jest.fn();
    const invalidValue = "03-12-199_";

    await render(DxcDateInputComponent, {
      componentProperties: {
        label: "test-input",
        onChange: {
          emit: onChange,
        } as any,
      },
      imports: [
        MatDayjsDateModule,
        MatNativeDateModule,
        MatInputModule,
        MatDatepickerModule,
        MdePopoverModule,
        DxcBoxModule,
        CommonModule,
        DxcTextInputModule,
      ],
      providers: [
        { provide: MAT_DATE_FORMATS, useValue: DAYJS_DATE_FORMATS },
        {
          provide: DateAdapter,
          useClass: DayjsDateAdapter,
          deps: [MAT_DATE_LOCALE, Platform],
        },
      ],
    });
    const input = <HTMLInputElement>screen.getByRole("textbox");

    input.focus();
    fireEvent.input(input, { target: { value: invalidValue } });

    expect(onChange).toHaveBeenCalledWith({
      value: invalidValue,
      error: undefined,
      date: undefined,
    });
  });

  test("onChange function is called when the user selects from the calendar", async () => {
    const onChange = jest.fn();

    await render(DxcDateInputComponent, {
      componentProperties: {
        label: "test-input",
        value: newValue,
        onChange: {
          emit: onChange,
        } as any,
      },
      imports: [
        MatDayjsDateModule,
        MatNativeDateModule,
        MatInputModule,
        MatDatepickerModule,
        MdePopoverModule,
        DxcBoxModule,
        CommonModule,
        DxcTextInputModule,
      ],
      providers: [
        { provide: MAT_DATE_FORMATS, useValue: DAYJS_DATE_FORMATS },
        {
          provide: DateAdapter,
          useClass: DayjsDateAdapter,
          deps: [MAT_DATE_LOCALE, Platform],
        },
      ],
    });
    const calendarIcon = screen.getByRole("calendarIcon");

    fireEvent.click(calendarIcon);
    fireEvent.click(screen.getByText("4"));
    waitFor(() => {
      expect(onChange).toHaveBeenCalledWith({
        value: "04-12-1995",
        date: new Date("04/12/1995"),
      });
    });
  });

  test("onChange function is called when the user selects from the calendar, the stringValue received by the function is the date with the correct format", async () => {
    const onChange = jest.fn();

    await render(DxcDateInputComponent, {
      componentProperties: {
        label: "test-input",
        value: "12-03-1995",
        format: "MM-DD-YYYY",
        onChange: {
          emit: onChange,
        } as any,
      },
      imports: [
        MatDayjsDateModule,
        MatNativeDateModule,
        MatInputModule,
        MatDatepickerModule,
        MdePopoverModule,
        DxcBoxModule,
        CommonModule,
        DxcTextInputModule,
      ],
      providers: [
        { provide: MAT_DATE_FORMATS, useValue: DAYJS_DATE_FORMATS },
        {
          provide: DateAdapter,
          useClass: DayjsDateAdapter,
          deps: [MAT_DATE_LOCALE, Platform],
        },
      ],
    });
    const calendarIcon = screen.getByRole("calendarIcon");

    fireEvent.click(calendarIcon);
    expect(screen.getByText("DECEMBER 1995"));
    expect(
      screen.getByText("3").classList.contains("mat-calendar-body-selected")
    ).toBeTruthy();
    fireEvent.click(screen.getByText("4"));
    waitFor(() => {
      expect(onChange).toHaveBeenCalledWith({
        value: "12-04-1995",
        date: new Date("04/12/1995"),
      });
    });
  });

  test("If the user types something, if controlled and without onChange, the value doesn´t change", async () => {
    const onChange = jest.fn();

    await render(DxcDateInputComponent, {
      componentProperties: {
        label: "test-input",
        value: newValue,
        onChange: {
          emit: onChange,
        } as any,
      },
      imports: [
        MatDayjsDateModule,
        MatNativeDateModule,
        MatInputModule,
        MatDatepickerModule,
        MdePopoverModule,
        DxcBoxModule,
        CommonModule,
        DxcTextInputModule,
      ],
      providers: [
        { provide: MAT_DATE_FORMATS, useValue: DAYJS_DATE_FORMATS },
        {
          provide: DateAdapter,
          useClass: DayjsDateAdapter,
          deps: [MAT_DATE_LOCALE, Platform],
        },
      ],
    });
    const calendarIcon = screen.getByRole("calendarIcon");

    fireEvent.click(calendarIcon);
    expect(screen.getByText("DECEMBER 1995"));
    expect(
      screen.getByText("3").classList.contains("mat-calendar-body-selected")
    ).toBeTruthy();
    fireEvent.click(screen.getByText("4"));
    waitFor(() => {
      expect(onChange).toHaveBeenCalledWith({
        value: "04-12-1995",
        date: new Date("04/12/1995"),
      });
    });

    fireEvent.click(calendarIcon);

    expect(screen.getByText("DECEMBER 1995"));
    waitFor(() => {
      expect(
        screen.getByText("3").classList.contains("mat-calendar-body-selected")
      ).toBeTruthy();
    });
  });

  test("controlled dxc-date", async () => {
    const onChange = jest.fn();
    const onBlur = jest.fn();

    await render(DxcDateInputComponent, {
      componentProperties: {
        label: "test-input",
        value: "03-12-1995",
        defaultValue: "12-04-1995",
        onChange: {
          emit: onChange,
        } as any,
        onBlur: {
          emit: onBlur,
        } as any,
      },
      imports: [
        MatDayjsDateModule,
        MatNativeDateModule,
        MatInputModule,
        MatDatepickerModule,
        MdePopoverModule,
        DxcBoxModule,
        CommonModule,
        DxcTextInputModule,
      ],
      providers: [
        { provide: MAT_DATE_FORMATS, useValue: DAYJS_DATE_FORMATS },
        {
          provide: DateAdapter,
          useClass: DayjsDateAdapter,
          deps: [MAT_DATE_LOCALE, Platform],
        },
      ],
    });
    expect(screen.getByDisplayValue("03-12-1995"));
    const input = <HTMLInputElement>screen.getByRole("textbox");

    input.focus();
    fireEvent.input(input, { target: { value: "03-10-1996" } });
    expect(onChange).toHaveBeenCalledWith({
      value: "03-10-1996",
      error: undefined,
      date: new Date("1996/10/03"),
    });
    expect(screen.getByDisplayValue("03-12-1995"));
    fireEvent.blur(input);
    waitFor(() => {
      expect(onBlur).toHaveBeenCalledWith({
        error: undefined,
        value: "03-12-1995",
        date: new Date("1995/12/03"),
      });
    });
  });
});
Example #25
Source File: dxc-accordionGroup.component.spec.ts    From halstack-angular with Apache License 2.0 4 votes vote down vote up
describe("DxcAccordion tests", () => {
  test("should render dxc-accordion-group uncontrolled", async () => {
    const projection1 = "Lorem ipsum dolor sit amet";
    const projection2 = "Consectetur adipiscing elit";
    const projection3 = "Maecenas enim ipsum";
    await render(
      `<dxc-accordion-group>
                  <dxc-accordion label="test-accordion1">${projection1}</dxc-accordion>
                  <dxc-accordion label="test-accordion2">${projection2}</dxc-accordion>
                  <dxc-accordion label="test-accordion3">${projection3}</dxc-accordion>
                </dxc-accordion-group>`,
      {
        declarations: [DxcAccordionGroupComponent],
        imports: [
          DxcAccordionGroupModule,
          DxcAccordionModule,
          MatExpansionModule,
        ],
        excludeComponentDeclaration: true,
      }
    );

    expect(screen.getByText("test-accordion1")).toBeTruthy();
    expect(screen.getByText("test-accordion2")).toBeTruthy();
    expect(screen.getByText("test-accordion3")).toBeTruthy();
    expect(screen.getAllByRole("button")[0].getAttribute("aria-expanded")).toBe(
      "false"
    );
    expect(screen.getAllByRole("button")[1].getAttribute("aria-expanded")).toBe(
      "false"
    );
    expect(screen.getAllByRole("button")[2].getAttribute("aria-expanded")).toBe(
      "false"
    );
  });

  test("Accordion Group Uncontrolled with undefined ActiveIndex", async () => {
    const projection1 = "Lorem ipsum dolor sit amet";
    const projection2 = "Consectetur adipiscing elit";
    const projection3 = "Maecenas enim ipsum";
    const accordions = await render(
      `<dxc-accordion-group [indexActive]="undefined">
                  <dxc-accordion label="test-accordion1">${projection1}</dxc-accordion>
                  <dxc-accordion label="test-accordion2">${projection2}</dxc-accordion>
                  <dxc-accordion label="test-accordion3">${projection3}</dxc-accordion>
                </dxc-accordion-group>`,
      {
        declarations: [DxcAccordionGroupComponent],
        imports: [
          DxcAccordionGroupModule,
          DxcAccordionModule,
          MatExpansionModule,
        ],
        excludeComponentDeclaration: true,
      }
    );

    expect(screen.getByText("test-accordion1")).toBeTruthy();
    expect(screen.getByText("test-accordion2")).toBeTruthy();
    expect(screen.getByText("test-accordion3")).toBeTruthy();

    expect(screen.getByText(projection1).hidden);
    expect(screen.getByText(projection2).hidden);
    expect(screen.getByText(projection3).hidden);

    expect(screen.getAllByRole("button")[0].getAttribute("aria-expanded")).toBe(
      "false"
    );
    expect(screen.getAllByRole("button")[1].getAttribute("aria-expanded")).toBe(
      "false"
    );
    expect(screen.getAllByRole("button")[2].getAttribute("aria-expanded")).toBe(
      "false"
    );
  });

  test("Accordion Group uncontrolled with function", async () => {
    const projection1 = "Lorem ipsum dolor sit amet";
    const projection2 = "Consectetur adipiscing elit";
    const onClickFunction = jest.fn();
    await render(
      `<dxc-accordion-group (onActiveChange)="onClickFunction($event)">
                  <dxc-accordion label="test-accordion1">${projection1}</dxc-accordion>
                  <dxc-accordion label="test-accordion2">${projection2}</dxc-accordion>
                </dxc-accordion-group>`,
      {
        componentProperties: { onClickFunction },
        imports: [
          DxcAccordionGroupModule,
          DxcAccordionModule,
          MatExpansionModule,
        ],
        declarations: [DxcAccordionGroupComponent],
        excludeComponentDeclaration: true,
      }
    );

    expect(screen.getByText("test-accordion1")).toBeTruthy();
    expect(screen.getByText("test-accordion2")).toBeTruthy();

    expect(screen.getByText(projection1).hidden);
    expect(screen.getByText(projection2).hidden);
    expect(screen.getAllByRole("button")[0].getAttribute("aria-expanded")).toBe(
      "false"
    );
    expect(screen.getAllByRole("button")[1].getAttribute("aria-expanded")).toBe(
      "false"
    );

    fireEvent.click(screen.getByText("test-accordion1"));
    expect(onClickFunction).toHaveBeenCalled();
    expect(screen.getByText(projection1).hidden).toBeFalsy();
    expect(screen.getByText(projection2).hidden);
    expect(screen.getAllByRole("button")[0].getAttribute("aria-expanded")).toBe(
      "true"
    );
    expect(screen.getAllByRole("button")[1].getAttribute("aria-expanded")).toBe(
      "false"
    );

    fireEvent.click(screen.getByText("test-accordion2"));
    expect(onClickFunction).toHaveBeenCalled();
    expect(screen.getByText(projection2).hidden).toBeFalsy();
    expect(screen.getByText(projection1).hidden);
    expect(screen.getAllByRole("button")[0].getAttribute("aria-expanded")).toBe(
      "false"
    );
    expect(screen.getAllByRole("button")[1].getAttribute("aria-expanded")).toBe(
      "true"
    );
  });

  test("Accordion Group Controlled with index active", async () => {
    const projection1 = "Lorem ipsum dolor sit amet";
    const projection2 = "Consectetur adipiscing elit";
    const onClickFunction = jest.fn();
    const indexActive = 0;
    const { rerender } = await render(
      `<dxc-accordion-group [indexActive]="indexActive">
                  <dxc-accordion label="test-accordion1">${projection1}</dxc-accordion>
                  <dxc-accordion label="test-accordion2">${projection2}</dxc-accordion>
                </dxc-accordion-group>`,
      {
        declarations: [DxcAccordionGroupComponent],
        componentProperties: { onClickFunction, indexActive: 0 },
        imports: [
          DxcAccordionGroupModule,
          DxcAccordionModule,
          MatExpansionModule,
        ],
        excludeComponentDeclaration: true,
      }
    );
    expect(screen.getByText("test-accordion1")).toBeTruthy();
    expect(screen.getByText("test-accordion2")).toBeTruthy();

    expect(screen.getByText(projection1)).toBeTruthy();
    expect(screen.getByText(projection2).hidden);

    expect(screen.getAllByRole("button")[0].getAttribute("aria-expanded")).toBe(
      "true"
    );
    expect(screen.getAllByRole("button")[1].getAttribute("aria-expanded")).toBe(
      "false"
    );

    await rerender({ indexActive: 1 });

    expect(screen.getAllByRole("button")[0].getAttribute("aria-expanded")).toBe(
      "false"
    );
    expect(screen.getAllByRole("button")[1].getAttribute("aria-expanded")).toBe(
      "true"
    );
  });

  test("Accordion Group Controlled with static index active and function", async () => {
    const projection1 = "Lorem ipsum dolor sit amet";
    const projection2 = "Consectetur adipiscing elit";
    const onClickFunction = jest.fn();
    await render(
      `<dxc-accordion-group  [indexActive]="null" (onActiveChange)="onClickFunction($event)">
                  <dxc-accordion label="test-accordion1">${projection1}</dxc-accordion>
                  <dxc-accordion label="test-accordion2">${projection2}</dxc-accordion>
                </dxc-accordion-group>`,
      {
        declarations: [DxcAccordionGroupComponent],
        componentProperties: { onClickFunction },
        imports: [
          DxcAccordionGroupModule,
          DxcAccordionModule,
          MatExpansionModule,
        ],
        excludeComponentDeclaration: true,
      }
    );

    expect(screen.getByText("test-accordion1")).toBeTruthy();
    expect(screen.getByText("test-accordion2")).toBeTruthy();

    fireEvent.click(screen.getByText("test-accordion1"));
    expect(onClickFunction).toHaveBeenCalled();

    expect(screen.getByText(projection1).hidden);
    expect(screen.getByText(projection2).hidden);

    expect(screen.getAllByRole("button")[0].getAttribute("aria-expanded")).toBe(
      "false"
    );
    expect(screen.getAllByRole("button")[1].getAttribute("aria-expanded")).toBe(
      "false"
    );
  });
});