swr#SWRConfig TypeScript Examples

The following examples show how to use swr#SWRConfig. 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: _app.tsx    From website with Apache License 2.0 7 votes vote down vote up
function MyApp({ Component, pageProps }: AppProps) {
  /* niceeeee */
  console.log(`
       __            __        __  __             ______    ______  
      /  |          /  |      /  |/  |           /      \  /      \ 
  ____$$ |  ______  $$ |____  $$ |$$/   ______  /$$$$$$  |/$$$$$$  |
 /    $$ | /      \ $$      \ $$ |/  | /      \ $$ |  $$ |$$ \__$$/ 
/$$$$$$$ | $$$$$$  |$$$$$$$  |$$ |$$ | $$$$$$  |$$ |  $$ |$$      \ 
$$ |  $$ | /    $$ |$$ |  $$ |$$ |$$ | /    $$ |$$ |  $$ | $$$$$$  |
$$ \__$$ |/$$$$$$$ |$$ |  $$ |$$ |$$ |/$$$$$$$ |$$ \__$$ |/  \__$$ |
$$    $$ |$$    $$ |$$ |  $$ |$$ |$$ |$$    $$ |$$    $$/ $$    $$/ 
 $$$$$$$/  $$$$$$$/ $$/   $$/ $$/ $$/  $$$$$$$/  $$$$$$/   $$$$$$/  
  `);

  const preferredTheme = usePreferredTheme();

  return (
    <StyledEngineProvider injectFirst>
      <SWRConfig
        value={{
          fetcher,
          refreshInterval: 12000000,
          revalidateOnFocus: false,
        }}
      >
        <ThemeProvider theme={preferredTheme === "dark" ? Theme : LightTheme}>
          <GlobalStyles />
          <Component {...pageProps} />
        </ThemeProvider>
      </SWRConfig>
    </StyledEngineProvider>
  );
}
Example #2
Source File: react-testing-library-config.tsx    From coindrop with GNU General Public License v3.0 6 votes vote down vote up
AllTheProviders = ({ children }) => {
  return (
    <SWRConfig value={{ dedupingInterval: 0 }}>
      <ChakraProvider theme={theme}>
          {children}
      </ChakraProvider>
    </SWRConfig>
  );
}
Example #3
Source File: query-data.tsx    From plasmic with MIT License 6 votes vote down vote up
export function PlasmicPrepassContext(
  props: PropsWithChildren<{
    cache: Map<string, any>;
  }>
) {
  const { cache, children } = props;
  return (
    <PrepassContext.Provider value={true}>
      <SWRConfig
        value={{
          provider: () => cache,
          suspense: true,
          fallback: {},
        }}
      >
        {children}
      </SWRConfig>
    </PrepassContext.Provider>
  );
}
Example #4
Source File: query-data.tsx    From plasmic with MIT License 6 votes vote down vote up
export function PlasmicQueryDataProvider(props: {
  suspense?: boolean;
  children: React.ReactNode;
  prefetchedCache?: Record<string, any>;
}) {
  const { children, suspense, prefetchedCache } = props;
  const prepass = React.useContext(PrepassContext);
  if (prepass) {
    // If we're in prepass, then there's already a wrappign SWRConfig;
    // don't interfere with it.
    return <>{children}</>;
  } else {
    return (
      <SWRConfig
        value={{
          fallback: prefetchedCache ?? {},
          suspense,
        }}
      >
        {children}
      </SWRConfig>
    );
  }
}
Example #5
Source File: App.tsx    From logseq-plugin-link-preview with MIT License 6 votes vote down vote up
function App() {
  useAdaptBackgroundColor();
  const appState = useAppStateStore();
  return (
    <SWRConfig value={{ provider: localStorageProvider }}>
      {appState.value.type === 'hovering' && <HoverLinkPreview />}
      {appState.value.type === 'prompt' && <Prompt />}
    </SWRConfig>
  );
}
Example #6
Source File: App.tsx    From nodestatus with MIT License 6 votes vote down vote up
App: FC = () => (
  <SWRConfig value={{
    fetcher: (url: string) => axios.get<IResp>(url).then(res => res.data),
    revalidateOnFocus: false
  }}
  >
    <Router basename="/admin">
      <Suspense fallback={<Loading />}>
        <GlobalRoutes />
      </Suspense>
    </Router>
  </SWRConfig>
)
Example #7
Source File: usePermission.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
function renderComponent(mockApi: PermissionApi) {
  return render(
    <SWRConfig value={{ provider: () => new Map() }}>
      <TestApiProvider apis={[[permissionApiRef, mockApi]]}>
        <TestComponent />
      </TestApiProvider>
      ,
    </SWRConfig>,
  );
}
Example #8
Source File: AgeChart.test.tsx    From crowdsource-dataplatform with MIT License 5 votes vote down vote up
describe('AgeChart', () => {
  const setup = async (language: string | undefined) => {
    fetchMock.doMockOnceIf('/aggregated-json/ageGroupContributions.json').mockResponseOnce(
      JSON.stringify([
        {
          age_group: 'upto 10',
          contributions: 10,
          hours_contributed: 0.45,
          hours_validated: 0.2,
          speakers: 3,
        },
        {
          age_group: '30 - 60',
          contributions: 15,
          hours_contributed: 0.5,
          hours_validated: 0.0,
          speakers: 1,
        },
      ])
    );

    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <AgeChart language={language} />
      </SWRConfig>
    );
    await waitFor(() => {
      expect(fetchMock).toBeCalled();
    });
    return renderResult;
  };

  it('should render the component and matches it against stored snapshot', async () => {
    const { asFragment } = await setup(undefined);

    expect(asFragment()).toMatchSnapshot();
  });

  it('should fetch data from ageGroupContributions when language not specified', async () => {
    await setup(undefined);

    expect(fetchMock).toBeCalledWith('/aggregated-json/ageGroupContributions.json');
  });
});
Example #9
Source File: index.tsx    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 5 votes vote down vote up
ReactDOM.render(
  <BrowserRouter>
    <SWRConfig value={swrConfig}>
      <App />
    </SWRConfig>
  </BrowserRouter>,
  document.getElementById('root') as HTMLElement,
);
Example #10
Source File: app.tsx    From fork-explorer with MIT License 5 votes vote down vote up
Ultra = ({ cache }: { cache: Cache }) => {
  return (
    <StoreProvider store={store}>
      <SWRConfig value={options(cache)}>
        <StoreStarter>
          <>
            <a
              href="https://github.com/hsjoberg/fork-explorer"
              className="github-corner"
              aria-label="View source on GitHub"
            >
              <svg width="80" height="80" viewBox="0 0 250 250" className="github-corner-svg" aria-hidden="true">
                <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
                <path
                  d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
                  fill="currentColor"
                  style={{ transformOrigin: "130px 106px" }}
                  className="octo-arm"
                ></path>
                <path
                  d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
                  fill="currentColor"
                  className="octo-body"
                ></path>
              </svg>
            </a>
            <main>
              <Switch>
                <Route path="/" component={Index} />
                <Route path="/miner/:miner">{(params: any) => <Miner miner={params.miner} />}</Route>
                <Route path="/miners">
                  <Miners />
                </Route>
                <Route path="/stats">
                  <Stats />
                </Route>
                <Route path="/about">
                  <About />
                </Route>
                <Route path="/settings">
                  <Settings />
                </Route>
                <Route>
                  <strong>404</strong>
                </Route>
              </Switch>
            </main>
          </>
        </StoreStarter>
      </SWRConfig>
    </StoreProvider>
  );
}
Example #11
Source File: ProgressChart.test.tsx    From crowdsource-dataplatform with MIT License 5 votes vote down vote up
describe('ProgressChart with language', () => {
  const setup = async (
    type: 'asr' | 'ocr' | 'text' | 'parallel',
    language: string | undefined,
    responseData: any
  ) => {
    fetchMock
      .doMockOnceIf('/aggregated-json/monthlyTimeline.json')
      .mockResponseOnce(JSON.stringify(responseData));

    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <ProgressChart type={type} language={language} />
      </SWRConfig>
    );
    await waitFor(() => expect(fetchMock).toBeCalled());
    return renderResult;
  };
  it('should fetch data from monthlyTimeline when language is specified', async () => {
    const data = [
      {
        year: 2021,
        month: 5,
        language: 'Hindi',
        cumulative_validations: 0,
        total_contribution_count: 1,
        total_validation_count: 0,
        type: 'asr',
      },
      {
        year: 2021,
        month: 6,
        language: 'Hindi',
        cumulative_contributions: 0.002,
        cumulative_validations: 0,
        total_contribution_count: 1,
        total_validation_count: 0,
        type: 'asr',
      },
      {
        year: 2021,
        month: 4,
        cumulative_contributions: 0.02,
        cumulative_validations: 0,
        total_contribution_count: 1,
        total_validation_count: 0,
        type: 'ocr',
      },
      {
        year: 2021,
        month: 7,
        cumulative_contributions: 0.102,
        cumulative_validations: 2.02,
        total_contribution_count: 1,
        total_validation_count: 2,
        type: 'ocr',
      },
    ];
    await setup('asr', 'Hindi', data);

    await waitFor(() => expect(fetchMock).toBeCalledWith('/aggregated-json/monthlyTimeline.json'));
  });
});
Example #12
Source File: ParticipationStats.test.tsx    From crowdsource-dataplatform with MIT License 5 votes vote down vote up
describe('ParticipationStats', () => {
  const setup = async () => {
    fetchMock.doMockOnceIf('/aggregated-json/participationStats.json').mockResponseOnce(
      JSON.stringify([
        {
          count: '9',
          type: 'asr',
        },
        {
          count: '283',
          type: 'text',
        },
        {
          count: '53',
          type: 'ocr',
        },
        {
          count: null,
          type: 'parallel',
        },
      ])
    );

    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <ParticipationStats />
      </SWRConfig>
    );
    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    return renderResult;
  };

  async () => {
    verifyAxeTest(await setup());
  };

  it('should render the component and matches it against stored snapshot', async () => {
    const { asFragment } = await setup();

    expect(asFragment()).toMatchSnapshot();
  });

  it('should render the result for landing page', async () => {
    await setup();
    expect(screen.getByText('ASR INITIATIVETEXTSUFFIX')).toBeInTheDocument();
    expect(screen.getByText('TTS INITIATIVETEXTSUFFIX')).toBeInTheDocument();
    expect(screen.getByText('OCR INITIATIVETEXTSUFFIX')).toBeInTheDocument();
    expect(screen.getByText('TRANSLATION INITIATIVETEXTSUFFIX')).toBeInTheDocument();
  });
});
Example #13
Source File: IndiaMapChart.test.tsx    From crowdsource-dataplatform with MIT License 5 votes vote down vote up
describe('IndiaMapChart without language', () => {
  const setup = async (type: 'asr' | 'ocr' | 'text' | 'parallel', language: string | undefined) => {
    fetchMock.doMockOnceIf('/aggregated-json/cumulativeDataByState.json').mockResponseOnce(
      JSON.stringify([
        {
          state: 'S1',
          total_speakers: 1,
          total_contributions: 0.001,
          total_validations: 0,
          total_contribution_count: 1,
          total_validation_count: 0,
          type: 'asr',
        },
        {
          state: 'Punjab',
          total_speakers: 3,
          total_contributions: 0.0,
          total_validations: 0,
          total_contribution_count: 1,
          total_validation_count: 6,
          type: 'ocr',
        },
      ])
    );

    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <IndiaMapChart type={type} language={language} />
      </SWRConfig>
    );
    await waitFor(() => {
      expect(fetchMock).toBeCalled();
    });
    return renderResult;
  };

  it('should render the component and matches it against stored snapshot', async () => {
    const { asFragment } = await setup('asr', undefined);

    expect(asFragment()).toMatchSnapshot();
  });

  it('should fetch data from cumulativeDataByState when language not specified', async () => {
    await setup('asr', undefined);

    expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByState.json');
  });

  it('should fetch data from CumulativeDataByState for ocr', async () => {
    await setup('ocr', undefined);

    expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByState.json');
  });
});
Example #14
Source File: _app.tsx    From pagely with MIT License 5 votes vote down vote up
MyApp = ({ Component, pageProps }) => {
  const router = useRouter();
  /**
   * If the current route is listed as public, render it directly.
   * Otherwise, use Clerk to require authentication.
   */
  return (
    <ClerkProvider>
      {privatePages.includes(router.pathname) ? (
        <>
          {process.env.NODE_ENV === 'production' && (
            <Script
              async
              defer
              data-website-id={process.env.NEXT_PUBLIC_ANALYTICS_ID}
              strategy='afterInteractive'
              src={process.env.NEXT_PUBLIC_ANALYTICS_URL}
            />
          )}
          <Head>
            <link rel='preconnect' href='https://fonts.googleapis.com' />
            <link
              rel='preconnect'
              href='https://fonts.gstatic.com'
              crossOrigin='true'
            />
            <link
              href='https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap'
              rel='stylesheet'
            />
          </Head>
          <SignedIn>
            <SWRConfig
              value={{
                fetcher: (url) => fetch(url).then((res) => res.json()),
              }}>
              <Component {...pageProps} />
            </SWRConfig>
          </SignedIn>
          <SignedOut>
            <RedirectToSignIn />
          </SignedOut>
        </>
      ) : (
        <>
          <Script
            async
            defer
            data-website-id={process.env.NEXT_PUBLIC_ANALYTICS_ID}
            strategy='afterInteractive'
            src={process.env.NEXT_PUBLIC_ANALYTICS_URL}
          />
          <Head>
            <link rel='preconnect' href='https://fonts.googleapis.com' />
            <link
              rel='preconnect'
              href='https://fonts.gstatic.com'
              crossOrigin='true'
            />
            <link
              href='https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap'
              rel='stylesheet'
            />
          </Head>
          <SWRConfig
            value={{
              fetcher: (url) => fetch(url).then((res) => res.json()),
            }}>
            <Component {...pageProps} />
          </SWRConfig>
        </>
      )}
    </ClerkProvider>
  );
}
Example #15
Source File: AgeChart.test.tsx    From crowdsource-dataplatform with MIT License 5 votes vote down vote up
describe('AgeChart with language', () => {
  const setup = async (language: string | undefined, responseData: any) => {
    fetchMock
      .doMockOnceIf('/aggregated-json/ageGroupAndLanguageContributions.json')
      .mockResponseOnce(JSON.stringify(responseData));

    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <AgeChart language={language} />
      </SWRConfig>
    );
    await waitFor(() => {
      expect(fetchMock).toBeCalled();
    });
    return renderResult;
  };

  it('should fetch data from ageGroupAndLanguageContributions when language is specified', async () => {
    const data = [
      {
        age_group: '30 - 60',
        contributions: 10,
        hours_contributed: 0.45,
        hours_validated: 0.2,
        speakers: 3,
        language: 'Hindi',
      },
    ];
    await setup('Hindi', data);
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/ageGroupAndLanguageContributions.json');
    });
  });

  it('should fetch data from ageGroupAndLanguageContributions without speakers param', async () => {
    const data = [
      {
        age_group: '30 - 60',
        contributions: 10,
        hours_contributed: 0.45,
        hours_validated: 0.2,
        language: 'Hindi',
      },
    ];
    await setup('Hindi', data);
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/ageGroupAndLanguageContributions.json');
    });
  });
});
Example #16
Source File: ContributionStatsByLanguage.test.tsx    From crowdsource-dataplatform with MIT License 5 votes vote down vote up
describe('ContributionStatsByLanguage', () => {
  const setup = async (initiative: 'tts' | 'asr' | 'translation' | 'ocr') => {
    fetchMock.doMockOnceIf('/aggregated-json/cumulativeDataByLanguage.json').mockResponseOnce(
      JSON.stringify([
        {
          language: 'English',
          total_speakers: 8,
          total_contributions: 0.039,
          total_validations: 0.0,
          total_contribution_count: 24,
          total_validation_count: 0,
          type: 'asr',
        },
        {
          language: 'Hindi',
          total_speakers: 6,
          total_contributions: 0.021,
          total_validations: 0.05,
          total_contribution_count: 20,
          total_validation_count: 2,
          type: 'asr',
        },
      ])
    );

    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <ContributionStatsByLanguage initiative={initiative} language="Hindi" handleNoData={() => {}} />
      </SWRConfig>
    );
    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    return renderResult;
  };

  async () => {
    verifyAxeTest(await setup('tts'));
  };

  it('should render the component and matches it against stored snapshot', async () => {
    const { asFragment } = await setup('tts');

    expect(asFragment()).toMatchSnapshot();
  });

  it('should render the result for initiative home page', async () => {
    await setup('tts');
    expect(screen.getByText('peopleParticipated')).toBeInTheDocument();
    expect(screen.getByText('durationTranscribed')).toBeInTheDocument();
    expect(screen.getByText('durationValidated')).toBeInTheDocument();
    expect(screen.getByText('1 minutes1')).toBeInTheDocument();
    expect(screen.getByText('3 minutes1')).toBeInTheDocument();
  });

  it('should display zeros when no data found for initiative', async () => {
    await setup('ocr');
    expect(screen.getByText('0')).toBeInTheDocument();
  });
});
Example #17
Source File: GenderChart.test.tsx    From crowdsource-dataplatform with MIT License 5 votes vote down vote up
describe('GenderChart', () => {
  const setup = async (language: string | undefined) => {
    fetchMock.doMockOnceIf('/aggregated-json/genderGroupContributions.json').mockResponseOnce(
      JSON.stringify([
        {
          gender: 'male',
          contributions: 10,
          hours_contributed: 0.45,
          hours_validated: 0.2,
          speakers: 3,
        },
        {
          gender: 'female',
          contributions: 10,
          hours_contributed: 0.45,
          hours_validated: 0.2,
          speakers: 3,
        },
        {
          gender: 'Transgender - He',
          contributions: 10,
          hours_contributed: 0.45,
          hours_validated: 0.2,
          speakers: 3,
        },
        {
          gender: '',
          contributions: 10,
          hours_contributed: 0.45,
          hours_validated: 0.2,
          speakers: 3,
        },
      ])
    );
    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <GenderChart language={language} />
      </SWRConfig>
    );
    await waitFor(() => {
      expect(fetchMock).toBeCalled();
    });
    return renderResult;
  };

  it('should render the component and matches it against stored snapshot', async () => {
    const { asFragment } = await setup(undefined);

    expect(asFragment()).toMatchSnapshot();
  });

  it('should fetch data from genderGroupContributions when language not specified', async () => {
    await setup(undefined);

    expect(fetchMock).toBeCalledWith('/aggregated-json/genderGroupContributions.json');
  });
});
Example #18
Source File: GenderChart.test.tsx    From crowdsource-dataplatform with MIT License 5 votes vote down vote up
describe('GenderChart with language', () => {
  const setup = async (language: string | undefined, responseData: any) => {
    fetchMock
      .doMockOnceIf('/aggregated-json/genderGroupAndLanguageContributions.json')
      .mockResponseOnce(JSON.stringify(responseData));
    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <GenderChart language={language} />
      </SWRConfig>
    );
    await waitFor(() => {
      expect(fetchMock).toBeCalled();
    });
    return renderResult;
  };

  it('should fetch data from genderGroupAndLanguageContributions when language is specified', async () => {
    const data = [
      {
        gender: 'male',
        contributions: 10,
        hours_contributed: 0.45,
        hours_validated: 0.2,
        speakers: 3,
        language: 'Hindi',
      },
    ];
    await setup('Hindi', data);
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/genderGroupAndLanguageContributions.json');
    });
  });

  it('should set the default value to 0 when hours_contributed is not present in api response', async () => {
    const data = [
      {
        gender: 'male',
        contributions: 10,
        hours_validated: 0.2,
        speakers: 3,
        language: 'Hindi',
      },
      {
        gender: 'female',
        contributions: 10,
        hours_validated: 0.2,
        speakers: 3,
        language: 'Hindi',
      },
      {
        gender: '',
        contributions: 10,
        hours_validated: 0.2,
        speakers: 3,
        language: 'Hindi',
      },
      {
        gender: 'transgender',
        contributions: 10,
        hours_validated: 0.2,
        speakers: 3,
        language: 'Hindi',
      },
    ];
    await setup('Hindi', data);
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/genderGroupAndLanguageContributions.json');
    });
  });
});
Example #19
Source File: TtsDashboard.test.tsx    From crowdsource-dataplatform with MIT License 4 votes vote down vote up
describe('TtsDashboard', () => {
  global.document.getElementById = jest.fn().mockImplementation(
    x =>
      x === 'float' && {
        style: {
          width: '50%',
        },
      }
  );

  const setup = async () => {
    fetchMock.doMockIf('/aggregated-json/cumulativeDataByLanguage.json').mockResponse(
      JSON.stringify([
        {
          language: 'English',
          total_contribution_count: 36,
          total_contributions: 0.057,
          total_speakers: 9,
          total_validation_count: 2,
          total_validations: 0.001,
          type: 'asr',
        },
      ])
    );
    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <TtsDashboard />
      </SWRConfig>
    );
    await screen.findByText('ContributionStats');
    return renderResult;
  };
  it('should contain language selector', async () => {
    await setup();
    expect(screen.getByRole('combobox', { name: 'Select Language' })).toBeInTheDocument();
  });

  it('changing language from language selector should update stats', async () => {
    await setup();
    expect(screen.getByRole('combobox', { name: 'Select Language' })).toBeInTheDocument();
    userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'English');
    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json');
    expect(screen.queryByText('languages')).not.toBeInTheDocument();
  });

  it('changing language from language selector should display nodata message when data not available', async () => {
    await setup();
    userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'English');
    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json');
    });
    await waitFor(() => {
      expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
    });
    await waitFor(() => expect(screen.queryByText('noDataMessageDashboard')).not.toBeInTheDocument());
    expect(screen.queryByText('languages')).not.toBeInTheDocument();
  });

  it('changing to language where data not available and clicking contribute now should display change user modal for new user', async () => {
    await setup();
    userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
    await waitFor(() => {
      expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
    });
    userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
    await waitFor(() => expect(screen.getByTestId('ChangeUserForm')).toBeInTheDocument());

    userEvent.click(screen.getByRole('button', { name: 'Close' }));

    await waitForElementToBeRemoved(() => screen.queryByTestId('ChangeUserModal'));
  });

  it('changing to language where data not available and clicking contribute now should redirect for existing user', async () => {
    when(localStorage.getItem)
      .calledWith('speakerDetails')
      .mockImplementation(
        () => '{"userName":"abc","motherTongue":"","age":"","gender":"","language":"English","toLanguage":""}'
      );
    when(localStorage.getItem)
      .calledWith('contributionLanguage')
      .mockImplementation(() => 'English');
    await setup();
    await waitFor(() => {
      expect(localStorage.getItem).toBeCalled();
    });
    userEvent.selectOptions(screen.getByRole('combobox', { name: 'Select Language' }), 'Bengali');
    await waitFor(() => {
      expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
    });
    userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
    await waitFor(() => expect(screen.queryByTestId('ChangeUserModal')).not.toBeInTheDocument());
  });
});
Example #20
Source File: TtsValidate.test.tsx    From crowdsource-dataplatform with MIT License 4 votes vote down vote up
describe('TtsValidate', () => {
  const storeUrl = '/store';
  const skipUrl = '/skip';
  const acceptUrl = '/validate/1717503/accept';
  const rejectUrl = '/validate/1717503/reject';
  const successResponse = { success: true };
  const locationInfo = {
    country: 'India',
    regionName: 'National Capital Territory of Delhi',
  };

  const speakerDetails = {
    userName: 'abc',
    motherTongue: '',
    age: '',
    gender: '',
    language: 'Hindi',
    toLanguage: '',
  };

  const contributionsData = JSON.stringify({
    data: [
      {
        contribution_id: 1717503,
        dataset_row_id: 1248712,
        sentence:
          'inbound/asr/English/newsonair.nic.in_09-08-2021_03-37/37_Regional-Shillong-English-0830-202131192011.wav',
        contribution: 'सोल को अगर आप नहीं देख सकते शीशा लगा करके आप जरूर देखिए',
        source_info: null,
      },
      {
        contribution_id: 1717502,
        dataset_row_id: 1248711,
        sentence:
          'inbound/asr/English/newsonair.nic.in_09-08-2021_03-37/37_Regional-Shillong-English-0830-202121195940.wav',
        contribution: 'नहीं देख सकते शीशा लगा करके आप जरूर देखिए',
        source_info: null,
      },
      {
        contribution_id: 1717501,
        dataset_row_id: 1248710,
        sentence:
          'inbound/asr/English/newsonair.nic.in_09-08-2021_03-37/37_Regional-Shillong-English-0830-202112711182.wav',
        contribution: 'आप जरूर देखिए',
        source_info: null,
      },
      {
        contribution_id: 1717497,
        dataset_row_id: 1248705,
        sentence:
          'inbound/asr/English/newsonair.nic.in_09-08-2021_03-37/37_Regional-Shillong-English-0830-202083094241.wav',
        contribution: 'देखिए',
        source_info: null,
      },
      {
        contribution_id: 1717496,
        dataset_row_id: 1248704,
        sentence:
          'inbound/asr/English/newsonair.nic.in_09-08-2021_03-37/37_Regional-Shillong-English-0830-20208293814.wav',
        contribution: 'देखिए',
        source_info: null,
      },
    ],
  });

  const setup = async () => {
    when(localStorage.getItem)
      .calledWith('contributionLanguage')
      .mockImplementation(() => 'Hindi');

    when(localStorage.getItem)
      .calledWith('locationInfo')
      .mockImplementation(() => JSON.stringify(locationInfo));

    when(localStorage.getItem)
      .calledWith('speakerDetails')
      .mockImplementation(() => JSON.stringify(speakerDetails));

    fetchMock
      .doMockOnceIf('/contributions/asr?from=Hindi&to=&username=abc')
      .mockResponseOnce(contributionsData);
    fetchMock.doMockIf(storeUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(skipUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(acceptUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(rejectUrl).mockResponse(JSON.stringify(successResponse));
    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <TtsValidate />
        <div id="report">
          <button>Stop Audio</button>
        </div>
      </SWRConfig>
    );

    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));

    return renderResult;
  };

  it('needs change and correct button should be disabled initially', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeDisabled();
  });

  it('play button and skip button should be enabled initially', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Play Icon play' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
  });

  it('should abort the audio when user clicks on report, test speaker, feedback button', async () => {
    await setup();

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    userEvent.click(screen.getByRole('button', { name: /Stop Audio/ }));

    await waitFor(() => {
      expect(screen.getByRole('img', { name: 'Play Icon' })).toBeInTheDocument();
    });
  });

  it('play button click should play audio and pause button should be enabled', async () => {
    await setup();

    expect(screen.getByRole('img', { name: 'Play Icon' })).toBeInTheDocument();

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    expect(screen.getByRole('img', { name: 'Pause Icon' })).toBeInTheDocument();
  });

  it('pause button click should pause audio and play button should be enabled', async () => {
    await setup();

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    expect(screen.getByRole('img', { name: 'Pause Icon' })).toBeInTheDocument();

    userEvent.click(screen.getByRole('img', { name: 'Pause Icon' }));

    expect(screen.getByRole('img', { name: 'Play Icon' })).toBeInTheDocument();
  });

  it('should enable needs change and correct button when full audio is played', async () => {
    await setup();

    await waitFor(() => expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeDisabled());
    await waitFor(() => expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeDisabled());

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() => screen.getByTestId('audioElement').dispatchEvent(new window.Event('ended')));
    await waitFor(() => expect(screen.getByRole('img', { name: 'Replay Icon' })).toBeInTheDocument());
    await waitFor(() => expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled());
    await waitFor(() => expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled());
  });

  it('should replay full audio is played and replay clicked', async () => {
    await setup();

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() => screen.getByTestId('audioElement').dispatchEvent(new window.Event('ended')));
    await waitFor(() => expect(screen.getByRole('img', { name: 'Replay Icon' })).toBeInTheDocument());
    userEvent.click(screen.getByRole('img', { name: 'Replay Icon' }));
    await waitFor(() => expect(screen.getByRole('img', { name: 'Pause Icon' })).toBeInTheDocument());
  });

  it('should show edit text area when needs change button clicked', async () => {
    await setup();

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() => screen.getByTestId('audioElement').dispatchEvent(new window.Event('ended')));
    await waitFor(() => expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled());
    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    expect(screen.queryByRole('button', { name: 'Edit Icon needsChange' })).not.toBeInTheDocument();

    expect(screen.getByRole('button', { name: 'cancel' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();

    expect(screen.getByRole('textbox', { name: 'originalText' })).toBeInTheDocument();
    expect(screen.getByRole('textbox', { name: 'yourEdit (hindi)' })).toBeInTheDocument();
    userEvent.click(screen.getByRole('button', { name: 'cancel' }));
    await waitFor(() => expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled());
  });

  it('should not enable submit for short edit', async () => {
    await setup();

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() => screen.getByTestId('audioElement').dispatchEvent(new window.Event('ended')));
    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    userEvent.clear(screen.getByRole('textbox', { name: 'yourEdit (hindi)' }));
    userEvent.type(screen.getByRole('textbox', { name: 'yourEdit (hindi)' }), 'बप');
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();
  });

  it('skip should show next text for valdiating', async () => {
    await setup();

    userEvent.click(screen.getByRole('button', { name: 'skip' }));
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/validate/1717503/skip', {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'asr',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Play Icon play' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
    expect(screen.getByText('2/5')).toBeInTheDocument();
  });

  it('correct should show next text for validating', async () => {
    await setup();

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() => screen.getByTestId('audioElement').dispatchEvent(new window.Event('ended')));
    await waitFor(() => expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled());
    userEvent.click(screen.getByRole('button', { name: 'Correct Icon correct' }));

    await waitFor(() =>
      expect(fetchMock).toBeCalledWith('/validate/1717503/accept', {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'asr',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      })
    );

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Play Icon play' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
    expect(screen.getByText('2/5')).toBeInTheDocument();
  });

  it('should show the error popup when api throw the error and close modal on clicking button', async () => {
    const url = '/validate/1717503/accept';
    const errorResponse = new Error('Some error');
    await setup();
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);
    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));
    await waitFor(() => screen.getByTestId('audioElement').dispatchEvent(new window.Event('ended')));
    await waitFor(() => expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled());
    userEvent.click(screen.getByRole('button', { name: 'Correct Icon correct' }));
    await waitFor(() =>
      expect(fetchMock).toBeCalledWith(url, {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'asr',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      })
    );

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Play Icon play' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
    expect(screen.getByText('2/5')).toBeInTheDocument();
    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });

    await waitFor(() => {
      expect(screen.queryByText('apiFailureError')).not.toBeInTheDocument();
    });
  });

  it('should call /store and /validate endpoint when a correction is done', async () => {
    await setup();

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() => screen.getByTestId('audioElement').dispatchEvent(new window.Event('ended')));
    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();
    userEvent.clear(screen.getByRole('textbox', { name: 'yourEdit (hindi)' }));
    userEvent.type(screen.getByRole('textbox', { name: 'yourEdit (hindi)' }), 'बपपप');
    await waitFor(() => {
      expect(screen.getByRole('button', { name: 'submit' })).toBeEnabled();
    });
    userEvent.click(screen.getByRole('button', { name: 'submit' }));
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(storeUrl, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          country: 'India',
          state: 'National Capital Territory of Delhi',
          language: 'Hindi',
          type: 'asr',
          sentenceId: 1248712,
          userInput: 'बपपप',
          speakerDetails: JSON.stringify({
            userName: 'abc',
          }),
        }),
      });
    });
    await waitFor(() => expect(screen.getByRole('img', { name: 'check' })).toBeInTheDocument());

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(rejectUrl, {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          country: 'India',
          state: 'National Capital Territory of Delhi',
          userName: 'abc',
          type: 'asr',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    await waitFor(() => expect(screen.queryByRole('img', { name: 'check' })).not.toBeInTheDocument());
  });

  it('should show no data text when fetch call gives no data', async () => {
    when(localStorage.getItem)
      .calledWith('contributionLanguage')
      .mockImplementation(() => 'Hindi');

    const speakerDetails = {
      userName: 'abc',
      motherTongue: '',
      age: '',
      gender: '',
      language: 'Hindi',
      toLanguage: '',
    };

    when(localStorage.getItem)
      .calledWith('speakerDetails')
      .mockImplementation(() => JSON.stringify(speakerDetails));

    fetchMock
      .doMockIf('/contributions/asr?from=Hindi&to=&username=abc')
      .mockResponse(JSON.stringify({ data: [] }));
    render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <TtsValidate />
      </SWRConfig>
    );
    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    await waitFor(() => {
      expect(screen.getByText('noDataMessage')).toBeInTheDocument();
    });
  });

  it('should throw the error for last sentence', async () => {
    await setup();
    const url = '/skip';
    const errorResponse = new Error('Some error');
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/validate/1717503/skip', {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'asr',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });

    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });

    // await waitFor(() => {
    //   expect(screen.queryByText('apiFailureError')).not.toBeInTheDocument();
    // });
  });

  it('should go to thank you page after 5 skip sentences', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/validate/1717503/skip', {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'asr',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Play Icon play' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeDisabled();
    expect(screen.getByText('5/5')).toBeInTheDocument();
  });

  it('should go to thank you page when user skip 4 and validate last sentence', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/validate/1717503/skip', {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'asr',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Play Icon play' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeDisabled();
    expect(screen.getByText('5/5')).toBeInTheDocument();
  });
});
Example #21
Source File: _app.page.tsx    From crowdsource-dataplatform with MIT License 4 votes vote down vote up
MyApp = ({ Component, pageProps }: MyAppProps) => {
  const router = useRouter();
  const routerRef = useRef(router);
  routerRef.current = router;

  const [, setContributionLanguage, , storageObj] = useLocalStorage<string>(
    localStorageConstants.contributionLanguage
  );
  const [showModal, setShowModal] = useState(false);
  const [hasError, setHasError] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');

  useEffect(() => {
    const isInitiativePage = INITIATIVES_URL.some(initiativeKey =>
      routerRef.current.pathname.includes(initiativeBaseRoute[initiativeKey])
    );

    if (
      storageObj.key === localStorageConstants.contributionLanguage &&
      storageObj.oldValue !== storageObj.newValue &&
      isInitiativePage &&
      routerRef.current.pathname !== '/404'
    ) {
      setShowModal(true);
    }
  }, [storageObj]);

  /* istanbul ignore next */
  const { mutate } = useFetchWithInit(apiPaths.setCookie, { revalidateOnMount: false });
  /* istanbul ignore next */
  useEffect(() => {
    if (!localStorage.getItem(localStorageConstants.locationInfo)) {
      const getLocationInfo = async () => {
        localStorage.setItem(localStorageConstants.locationInfo, JSON.stringify(await fetchLocationInfo()));
      };
      getLocationInfo();
      mutate();
    }
  }, [mutate]);

  /* istanbul ignore next */
  const closeModal = () => {
    setShowModal(false);
    setContributionLanguage(storageObj.newValue);
  };

  return (
    <SSRProvider>
      <SWRConfig
        value={{
          /* istanbul ignore next */
          onError: error => {
            /* istanbul ignore next */
            if (error) {
              setHasError(true);
              if (error.status && error.status === ErrorStatusCode.SERVICE_UNAVAILABLE) {
                setErrorMsg('multipleRequestApiError');
              } else {
                setErrorMsg('apiFailureError');
              }
            }
          },
        }}
      >
        <Layout>
          <Component {...pageProps} />
          {router.pathname !== '/404' && <Float />}
          <LanguageChangeNotification
            show={showModal}
            onHide={closeModal}
            oldValue={storageObj.oldValue}
            newValue={storageObj.newValue}
          />
          <ErrorPopup
            show={hasError}
            onHide={() => {
              /* istanbul ignore next */
              setHasError(false);
            }}
            errorMsg={errorMsg}
          />
        </Layout>
      </SWRConfig>
    </SSRProvider>
  );
}
Example #22
Source File: _app.tsx    From website with Apache License 2.0 4 votes vote down vote up
export default function App({Component, pageProps, router}: AppProps) {
	const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
	const [hasScrolled, setHasScrolled] = useState(false);

	const ballCanvas = useRef<HTMLDivElement>(null);

	const toggleMenu = () => {
		setMobileMenuOpen(old => !old);
	};

	useEffect(() => {
		if (mobileMenuOpen) {
			document.body.style.overflow = 'hidden';
			return;
		}

		document.body.style.overflow = 'unset';
	}, [mobileMenuOpen]);

	useEffect(() => {
		if (typeof window === 'undefined' || !ballCanvas.current) {
			return;
		}

		return loadCursor(ballCanvas.current);
	}, []);

	useEffect(() => {
		if (typeof window === 'undefined') {
			return;
		}

		setMobileMenuOpen(false);

		void new Audio('/pop.mp3').play().catch(() => null);
	}, [router.pathname]);

	useEffect(() => {
		if (typeof window === 'undefined') {
			return;
		}

		const listener = () => {
			setHasScrolled(window.scrollY > 20);
		};

		document.addEventListener('scroll', listener);

		return () => {
			document.removeEventListener('scroll', listener);
		};
	}, []);

	const closeMenu = () => {
		setMobileMenuOpen(false);
	};

	const navLinks = (
		<>
			<NavLink href="/" closeMenu={closeMenu}>
				/
			</NavLink>
			<NavLink href="/about" closeMenu={closeMenu}>
				/about
			</NavLink>
			<NavLink href="/talk" closeMenu={closeMenu}>
				/talk
			</NavLink>
			<li className="shrink-0">
				<a
					target="_blank"
					href="https://alistair.blog"
					rel="noreferrer"
					className={navlinkClassname}
				>
					notes ↗️
				</a>
			</li>
		</>
	);

	return (
		<StrictMode>
			<SWRConfig
				value={{
					fallback: {
						// SSR Lanyard's data
						[`lanyard:${DISCORD_ID}`]: pageProps?.lanyard as unknown,
						'https://gh-pinned-repos.egoist.sh/?username=alii':
							pageProps?.pinnedRepos as unknown,
					},
					fetcher,
				}}
			>
				<Toaster toastOptions={{position: 'top-left'}} />

				<Head>
					<title>Alistair Smith</title>
				</Head>

				<AnimatePresence>
					{mobileMenuOpen && (
						<motion.div
							initial={{opacity: 0, y: -10}}
							animate={{opacity: 1, y: 0}}
							exit={{opacity: 0}}
							className="fixed inset-0 z-10 py-24 px-8 space-y-2 bg-white dark:bg-gray-900 sm:hidden"
						>
							<h1 className="text-4xl font-bold">Menu.</h1>

							<ul className="grid grid-cols-1 gap-2">{navLinks}</ul>
						</motion.div>
					)}
				</AnimatePresence>

				<div className="overflow-hidden sticky top-0 z-20 h-32 transition-all sm:hidden">
					<div
						className={`${
							hasScrolled || mobileMenuOpen ? 'mt-0' : 'mt-10 mx-5'
						} bg-gray-100 dark:bg-gray-900 relative transition-all ${
							hasScrolled || mobileMenuOpen ? 'rounded-none' : 'rounded-lg'
						}`}
					>
						<div
							className={`pr-5 flex justify-between transition-colors space-x-2 ${
								mobileMenuOpen
									? 'bg-gray-100 dark:bg-gray-800'
									: 'bg-transparent'
							}`}
						>
							<button
								type="button"
								className="block relative z-50 px-2 text-gray-500 focus:ring transition-all"
								onClick={toggleMenu}
							>
								<Hamburger
									toggled={mobileMenuOpen}
									size={20}
									color="currentColor"
								/>
							</button>

							<div className="overflow-hidden py-2 px-1">
								<Song />
							</div>
						</div>
					</div>
				</div>

				<div className="py-10 px-5 mx-auto max-w-4xl">
					<div className="hidden items-center space-x-2 sm:flex">
						<nav className="flex-1">
							<ul className="flex space-x-4">{navLinks}</ul>
						</nav>

						<div className="overflow-hidden py-2 px-1">
							<Song />
						</div>
					</div>

					<main className="mx-auto space-y-12 max-w-3xl md:py-24">
						<Component {...pageProps} />
					</main>

					<footer className="p-4 py-10 mx-auto mt-20 max-w-3xl border-t-2 border-gray-900/10 dark:border-white/10 opacity-50">
						<h1 className="text-3xl font-bold">Alistair Smith</h1>
						<p>Software Engineer • {new Date().getFullYear()}</p>
					</footer>
				</div>

				<div
					ref={ballCanvas}
					className="fixed z-30 w-6 h-6 bg-transparent rounded-full border border-black dark:border-white shadow-md opacity-0 duration-200 pointer-events-none ball-transitions"
				/>
			</SWRConfig>
		</StrictMode>
	);
}
Example #23
Source File: OcrValidate.test.tsx    From crowdsource-dataplatform with MIT License 4 votes vote down vote up
describe('OcrValidate', () => {
  const storeUrl = '/store';
  const skipUrl = '/validate/1717503/skip';
  const acceptUrl = '/validate/1717503/accept';
  const rejectUrl = '/validate/1717503/reject';
  const successResponse = { success: true };

  const speakerDetails = {
    userName: 'abc',
    motherTongue: '',
    age: '',
    gender: '',
    language: 'Hindi',
    toLanguage: '',
  };

  const locationInfo = {
    country: 'Test Country',
    regionName: 'Sample Region',
  };

  const contributionsData = JSON.stringify({
    data: [
      {
        contribution_id: 1717503,
        dataset_row_id: 1248712,
        sentence: 'inbound/ocr/Hindi/test.png',
        contribution: 'सोल को अगर आप नहीं देख',
      },
      {
        contribution_id: 1717502,
        dataset_row_id: 1248711,
        sentence: 'inbound/ocr/Hindi/test2.png',
        contribution: 'नहीं देख सकते शीशा लगा करके आप जरूर देखिए',
      },
      {
        contribution_id: 1717501,
        dataset_row_id: 1248710,
        sentence: 'inbound/ocr/Hindi/test3.png',
        contribution: 'आप जरूर देखिए',
      },
      {
        contribution_id: 1717497,
        dataset_row_id: 1248705,
        sentence: 'inbound/ocr/Hindi/test4.png',
        contribution: 'देखिए',
      },
      {
        contribution_id: 1717496,
        dataset_row_id: 1248704,
        sentence: 'inbound/ocr/Hindi/test5.png',
        contribution: 'देखिए',
      },
    ],
  });

  const setup = async () => {
    when(localStorage.getItem)
      .calledWith('contributionLanguage')
      .mockImplementation(() => 'Hindi');

    when(localStorage.getItem)
      .calledWith('speakerDetails')
      .mockImplementation(() => JSON.stringify(speakerDetails));

    when(localStorage.getItem)
      .calledWith('locationInfo')
      .mockImplementation(() => JSON.stringify(locationInfo));

    fetchMock
      .doMockOnceIf('/contributions/ocr?from=Hindi&to=&username=abc')
      .mockResponseOnce(contributionsData);
    fetchMock.doMockIf(storeUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(skipUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(acceptUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(rejectUrl).mockResponse(JSON.stringify(successResponse));
    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <OcrValidate />
      </SWRConfig>
    );

    await waitFor(() => expect(screen.queryByTestId('PageSpinner')).not.toBeInTheDocument());

    return renderResult;
  };

  it('needs change and correct button should be enabled initially', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
  });

  it('should show edit text area when needs change button clicked', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    expect(screen.queryByRole('button', { name: 'Edit Icon needsChange' })).not.toBeInTheDocument();

    expect(screen.getByRole('button', { name: 'cancel' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();

    expect(screen.getByRole('textbox', { name: 'yourEdit (hindi)' })).toBeInTheDocument();
    userEvent.click(screen.getByRole('button', { name: 'cancel' }));
    await waitFor(() => expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled());
  });

  it('should expand the  image', async () => {
    await setup();

    expect(screen.getByTestId('ExpandView')).toBeInTheDocument();
    expect(screen.getByAltText('OCR Data')).toBeInTheDocument();

    userEvent.click(screen.getByTestId('ExpandView'));

    await waitFor(() => {
      expect(screen.getByTestId('CollapseView')).toBeInTheDocument();
      expect(screen.getByAltText('OCR Data Expanded')).toBeInTheDocument();
    });
  });

  it('should not enable submit for short edit', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    userEvent.clear(screen.getByRole('textbox', { name: 'yourEdit (hindi)' }));
    userEvent.type(screen.getByRole('textbox', { name: 'yourEdit (hindi)' }), 'ab');
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();
  });

  it('skip should show next text for valdiating', async () => {
    await setup();

    userEvent.click(screen.getByRole('button', { name: 'skip' }));
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(skipUrl, {
        body:
          expect.stringContaining('"userName":"abc"') &&
          expect.stringContaining('"fromLanguage":"Hindi"') &&
          expect.stringContaining('"sentenceId":"1248712"') &&
          expect.stringContaining('"type":"ocr"'),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
    expect(screen.getByText('2/5')).toBeInTheDocument();
  });

  it('correct should show next text for validating', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Correct Icon correct' }));

    await waitFor(() =>
      expect(fetchMock).toBeCalledWith(acceptUrl, {
        body:
          expect.stringContaining('"userName":"abc"') &&
          expect.stringContaining('"fromLanguage":"Hindi"') &&
          expect.stringContaining('"sentenceId":"1248712"') &&
          expect.stringContaining('"type":"ocr"'),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      })
    );

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
    expect(screen.getByText('2/5')).toBeInTheDocument();
  });

  it('should show the error popup when api throw the error and close modal on clicking button', async () => {
    const url = '/validate/1717503/accept';
    const errorResponse = new Error('Some error');
    await setup();
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Correct Icon correct' }));
    await waitFor(() =>
      expect(fetchMock).toBeCalledWith(url, {
        body:
          expect.stringContaining('"userName":"abc"') &&
          expect.stringContaining('"fromLanguage":"Hindi"') &&
          expect.stringContaining('"sentenceId":"1248712"') &&
          expect.stringContaining('"type":"ocr"'),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      })
    );

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
    expect(screen.getByText('2/5')).toBeInTheDocument();
    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });

    await waitFor(() => {
      expect(screen.queryByText('apiFailureError')).not.toBeInTheDocument();
    });
  });

  it('should show the error popup for 2nd sentence when api throw the error and modal should close on clicking button', async () => {
    const url = '/validate/1717503/skip';
    const errorResponse = new Error('Some error');
    await setup();
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    userEvent.click(screen.getByRole('button', { name: 'skip' }));
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(skipUrl, {
        body:
          expect.stringContaining('"userName":"abc"') &&
          expect.stringContaining('"fromLanguage":"Hindi"') &&
          expect.stringContaining('"sentenceId":"1248712"') &&
          expect.stringContaining('"type":"ocr"'),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });

    await waitFor(() => {
      expect(screen.queryByText('apiFailureError')).not.toBeInTheDocument();
    });
  });

  it('should call /store and /validate endpoint when a correction is done', async () => {
    await setup();

    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();
    userEvent.clear(screen.getByRole('textbox', { name: 'yourEdit (hindi)' }));
    userEvent.type(screen.getByRole('textbox', { name: 'yourEdit (hindi)' }), 'बपपप');

    await waitFor(() => {
      expect(screen.getByRole('button', { name: 'submit' })).toBeEnabled();
    });
    userEvent.click(screen.getByRole('button', { name: 'submit' }));

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(storeUrl, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body:
          expect.stringContaining('"speakerDetails":{"userName":"abc"}') &&
          expect.stringContaining('"language":"Hindi"') &&
          expect.stringContaining('"sentenceId":"1248712"') &&
          expect.stringContaining('"type":"ocr"'),
      });
    });
    await waitFor(() => expect(screen.getByRole('img', { name: 'check' })).toBeInTheDocument());

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(rejectUrl, {
        body:
          expect.stringContaining('"userName":"abc"') &&
          expect.stringContaining('"fromLanguage":"Hindi"') &&
          expect.stringContaining('"sentenceId":"1248712"') &&
          expect.stringContaining('"type":"ocr"'),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    await waitFor(() => expect(screen.queryByRole('img', { name: 'check' })).not.toBeInTheDocument());
  });

  it('should show no data text when fetch call gives no data', async () => {
    when(localStorage.getItem)
      .calledWith('contributionLanguage')
      .mockImplementation(() => 'Hindi');

    const speakerDetails = {
      userName: 'abc',
      motherTongue: '',
      age: '',
      gender: '',
      language: 'Hindi',
      toLanguage: '',
    };

    when(localStorage.getItem)
      .calledWith('speakerDetails')
      .mockImplementation(() => JSON.stringify(speakerDetails));

    fetchMock
      .doMockIf('/contributions/ocr?from=Hindi&to=&username=abc')
      .mockResponse(JSON.stringify({ data: [] }));
    render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <OcrValidate />
      </SWRConfig>
    );
    await waitFor(() => expect(screen.queryByTestId('PageSpinner')).not.toBeInTheDocument());
    await waitFor(() => {
      expect(screen.getByText('noDataMessage')).toBeInTheDocument();
    });
  });

  it('should go to thank you page after 5 skip sentences', async () => {
    const url = '/validate/1717503/skip';
    const errorResponse = new Error('Some error');
    await setup();
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(skipUrl, {
        body:
          expect.stringContaining('"userName":"abc"') &&
          expect.stringContaining('"fromLanguage":"Hindi"') &&
          expect.stringContaining('"sentenceId":"1248712"') &&
          expect.stringContaining('"type":"ocr"'),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });
  });

  it('should go to thank you page after 4 skip sentences and last sentence throw an error when user submit', async () => {
    const errorResponse = new Error('Some error');
    await setup();
    fetchMock.doMockOnceIf(storeUrl).mockRejectOnce(errorResponse);

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });

    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();
    userEvent.clear(screen.getByRole('textbox', { name: 'yourEdit (hindi)' }));
    userEvent.type(screen.getByRole('textbox', { name: 'yourEdit (hindi)' }), 'बपपप');

    await waitFor(() => {
      expect(screen.getByRole('button', { name: 'submit' })).toBeEnabled();
    });
    userEvent.click(screen.getByRole('button', { name: 'submit' }));

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(storeUrl, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body:
          expect.stringContaining('"speakerDetails":{"userName":"abc"}') &&
          expect.stringContaining('"language":"Hindi"') &&
          expect.stringContaining('"sentenceId":"1248712"') &&
          expect.stringContaining('"type":"ocr"'),
      });
    });
    await waitFor(() => expect(screen.getByRole('img', { name: 'check' })).toBeInTheDocument());

    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });
  });
});
Example #24
Source File: TranslationValidate.test.tsx    From crowdsource-dataplatform with MIT License 4 votes vote down vote up
describe('TranslationValidate', () => {
  const storeUrl = '/store';
  const skipUrl = '/skip';
  const acceptUrl = '/validate/1719084/accept';
  const rejectUrl = '/validate/1719084/reject';
  const successResponse = { success: true };
  const locationInfo = {
    country: 'India',
    regionName: 'National Capital Territory of Delhi',
  };

  const speakerDetails = {
    userName: 'abc',
    motherTongue: '',
    age: '',
    gender: '',
    language: 'Hindi',
    toLanguage: '',
  };

  const contributionsData = JSON.stringify({
    data: [
      {
        contribution: '্্্্্্',
        contribution_id: 1719084,
        dataset_row_id: 1323119,
        sentence: 'ଆପଣ କେଉଁଠାରେ ବାସ କରନ୍ତି',
        source_info: null,
      },
      {
        contribution: '্্্্্্',
        contribution_id: 1719085,
        dataset_row_id: 1323119,
        sentence: 'ଆପଣ କେଉଁଠାରେ ବାସ କରନ୍ତି',
        source_info: null,
      },
      {
        contribution: '্্্্্্',
        contribution_id: 1719086,
        dataset_row_id: 1323119,
        sentence: 'ଆପଣ କେଉଁଠାରେ ବାସ କରନ୍ତି',
        source_info: null,
      },
      {
        contribution: '্্্্্্',
        contribution_id: 1719087,
        dataset_row_id: 1323119,
        sentence: 'ଆପଣ କେଉଁଠାରେ ବାସ କରନ୍ତି',
        source_info: null,
      },
      {
        contribution: '্্্্্্',
        contribution_id: 1719088,
        dataset_row_id: 1323119,
        sentence: 'ଆପଣ କେଉଁଠାରେ ବାସ କରନ୍ତି',
        source_info: null,
      },
    ],
  });

  const setup = async () => {
    when(localStorage.getItem)
      .calledWith('contributionLanguage')
      .mockImplementation(() => 'Hindi');

    when(localStorage.getItem)
      .calledWith('translatedLanguage')
      .mockImplementation(() => 'English');

    when(localStorage.getItem)
      .calledWith('locationInfo')
      .mockImplementation(() => JSON.stringify(locationInfo));

    when(localStorage.getItem)
      .calledWith('speakerDetails')
      .mockImplementation(() => JSON.stringify(speakerDetails));

    fetchMock
      .doMockOnceIf('/contributions/parallel?from=Hindi&to=English&username=abc')
      .mockResponseOnce(contributionsData);
    fetchMock.doMockIf(storeUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(skipUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(acceptUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(rejectUrl).mockResponse(JSON.stringify(successResponse));
    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <TranslationValidate />
      </SWRConfig>
    );

    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));

    return renderResult;
  };

  it('needs change and correct button should be disabled initially', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
  });

  it('should show edit text area when needs change button clicked', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    expect(screen.queryByRole('button', { name: 'Edit Icon needsChange' })).not.toBeInTheDocument();

    expect(screen.getByRole('button', { name: 'cancel' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();

    expect(screen.getByRole('textbox', { name: 'yourEdit (english)' })).toBeInTheDocument();
    userEvent.click(screen.getByRole('button', { name: 'cancel' }));
    await waitFor(() => expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled());
  });

  it('should not enable submit for short edit', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    userEvent.clear(screen.getByRole('textbox', { name: 'yourEdit (english)' }));
    userEvent.type(screen.getByRole('textbox', { name: 'yourEdit (english)' }), 'ab');
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();
  });

  it('skip should show next text for valdiating', async () => {
    await setup();

    userEvent.click(screen.getByRole('button', { name: 'skip' }));
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/validate/1719084/skip', {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          language: 'English',
          sentenceId: 1323119,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'parallel',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
    expect(screen.getByText('2/5')).toBeInTheDocument();
  });

  it('correct should show next text for validating', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Correct Icon correct' }));

    await waitFor(() =>
      expect(fetchMock).toBeCalledWith('/validate/1719084/accept', {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          language: 'English',
          sentenceId: 1323119,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'parallel',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      })
    );

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
    expect(screen.getByText('2/5')).toBeInTheDocument();
  });

  it('should show the error popup when api throw the error and close modal on clicking button', async () => {
    const url = '/validate/1719084/accept';
    const errorResponse = new Error('Some error');
    await setup();
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Correct Icon correct' }));
    await waitFor(() =>
      expect(fetchMock).toBeCalledWith(url, {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          language: 'English',
          sentenceId: 1323119,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'parallel',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      })
    );

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
    expect(screen.getByText('2/5')).toBeInTheDocument();
    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });

    await waitFor(() => {
      expect(screen.queryByText('apiFailureError')).not.toBeInTheDocument();
    });
  });

  it('should show the error popup for 2nd sentence when api throw the error and modal should close on clicking button', async () => {
    const url = '/validate/1719084/skip';
    const errorResponse = new Error('Some error');
    await setup();
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    userEvent.click(screen.getByRole('button', { name: 'skip' }));
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(url, {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          language: 'English',
          sentenceId: 1323119,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'parallel',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });

    await waitFor(() => {
      expect(screen.queryByText('apiFailureError')).not.toBeInTheDocument();
    });
  });

  it('should call /store and /validate endpoint when a correction is done', async () => {
    await setup();

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();
    userEvent.clear(screen.getByRole('textbox', { name: 'yourEdit (english)' }));
    userEvent.type(screen.getByRole('textbox', { name: 'yourEdit (english)' }), 'abcd');
    await waitFor(() => {
      expect(screen.getByRole('button', { name: 'submit' })).toBeEnabled();
    });
    userEvent.click(screen.getByRole('button', { name: 'submit' }));
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(storeUrl, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          country: 'India',
          state: 'National Capital Territory of Delhi',
          language: 'English',
          type: 'parallel',
          sentenceId: 1323119,
          userInput: 'abcd',
          speakerDetails: JSON.stringify({
            userName: 'abc',
          }),
          fromLanguage: 'Hindi',
        }),
      });
    });
    await waitFor(() => expect(screen.getByRole('img', { name: 'check' })).toBeInTheDocument());

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(rejectUrl, {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          fromLanguage: 'Hindi',
          sentenceId: 1323119,
          country: 'India',
          language: 'English',
          state: 'National Capital Territory of Delhi',
          userName: 'abc',
          type: 'parallel',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    await waitFor(() => expect(screen.queryByRole('img', { name: 'check' })).not.toBeInTheDocument());
  });

  it('should show no data text when fetch call gives no data', async () => {
    when(localStorage.getItem)
      .calledWith('contributionLanguage')
      .mockImplementation(() => 'Hindi');

    when(localStorage.getItem)
      .calledWith('translatedLanguage')
      .mockImplementation(() => 'English');

    const speakerDetails = {
      userName: 'abc',
      motherTongue: '',
      age: '',
      gender: '',
      language: 'Hindi',
      toLanguage: '',
    };

    when(localStorage.getItem)
      .calledWith('speakerDetails')
      .mockImplementation(() => JSON.stringify(speakerDetails));

    fetchMock
      .doMockIf('/contributions/parallel?from=Hindi&to=English&username=abc')
      .mockResponse(JSON.stringify({ data: [] }));
    render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <TranslationValidate />
      </SWRConfig>
    );
    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    await waitFor(() => {
      expect(screen.getByText('noDataMessage')).toBeInTheDocument();
    });
  });

  it('should go to thank you page after 5 skip sentences', async () => {
    const url = '/validate/1719084/skip';
    const errorResponse = new Error('Some error');
    await setup();
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(url, {
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          language: 'English',
          sentenceId: 1323119,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'parallel',
        }),
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        mode: 'cors',
      });
    });
    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });
  });

  it('should go to thank you page after 4 skip sentences and last sentence throw an error when user submit', async () => {
    const errorResponse = new Error('Some error');
    await setup();
    fetchMock.doMockOnceIf(storeUrl).mockRejectOnce(errorResponse);

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });

    expect(screen.getByRole('button', { name: 'Edit Icon needsChange' })).toBeEnabled();
    userEvent.click(screen.getByRole('button', { name: 'Edit Icon needsChange' }));
    expect(screen.getByRole('button', { name: 'submit' })).toBeDisabled();
    userEvent.clear(screen.getByRole('textbox', { name: 'yourEdit (english)' }));
    userEvent.type(screen.getByRole('textbox', { name: 'yourEdit (english)' }), 'abcd');
    await waitFor(() => {
      expect(screen.getByRole('button', { name: 'submit' })).toBeEnabled();
    });
    userEvent.click(screen.getByRole('button', { name: 'submit' }));

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(storeUrl, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          country: 'India',
          state: 'National Capital Territory of Delhi',
          language: 'English',
          type: 'parallel',
          sentenceId: 1323119,
          userInput: 'abcd',
          speakerDetails: JSON.stringify({
            userName: 'abc',
          }),
          fromLanguage: 'Hindi',
        }),
      });
    });
    await waitFor(() => expect(screen.getByRole('img', { name: 'check' })).toBeInTheDocument());

    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });
  });
});
Example #25
Source File: TranslationDashboard.test.tsx    From crowdsource-dataplatform with MIT License 4 votes vote down vote up
describe('TranslationDashboard', () => {
  global.document.getElementById = jest.fn().mockImplementation(
    x =>
      x === 'float' && {
        style: {
          width: '50%',
        },
      }
  );

  const fromLanguageElement = () => screen.getByRole('combobox', { name: 'Select From Language' });
  const toLanguageElement = () => screen.getByRole('combobox', { name: 'Select To Language' });

  const setup = async () => {
    fetchMock.doMockIf('/aggregated-json/cumulativeDataByLanguage.json').mockResponse(
      JSON.stringify([
        {
          language: 'English-Hindi',
          total_contribution_count: 36,
          total_contributions: 0.057,
          total_speakers: 9,
          total_validation_count: 2,
          total_validations: 0.001,
          type: 'parallel',
        },
      ])
    );
    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <TranslationDashboard />
      </SWRConfig>
    );
    await screen.findByText('ContributionStats');
    return renderResult;
  };

  it('should contain language selector', async () => {
    await setup();
    expect(fromLanguageElement()).toBeInTheDocument();
    expect(toLanguageElement()).toBeInTheDocument();
    expect(toLanguageElement()).toBeDisabled();
  });

  it('changing language in language pair selector should update stats', async () => {
    await setup();
    userEvent.selectOptions(fromLanguageElement(), 'English');
    expect(toLanguageElement()).toBeEnabled();
    userEvent.selectOptions(toLanguageElement(), 'Hindi');
    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json');
    expect(screen.queryByText('languages')).not.toBeInTheDocument();
  });

  it('changing from language back to all should show all language stats', async () => {
    await setup();
    userEvent.selectOptions(fromLanguageElement(), 'English');
    expect(toLanguageElement()).toBeEnabled();
    userEvent.selectOptions(fromLanguageElement(), 'all');
    expect(fromLanguageElement()).toHaveValue('all');
    expect(toLanguageElement()).toHaveValue('all');
  });

  it('should show default languages when all languages selected in to language dropdown', async () => {
    await setup();
    userEvent.selectOptions(fromLanguageElement(), 'English');
    userEvent.selectOptions(toLanguageElement(), 'Hindi');
    userEvent.selectOptions(toLanguageElement(), 'all');
    await waitFor(() => expect(fromLanguageElement()).toHaveValue('all'));
    await waitFor(() => expect(toLanguageElement()).toHaveValue('all'));
  });

  it('changing language from language pair selector should display nodata message when data not available', async () => {
    await setup();
    userEvent.selectOptions(fromLanguageElement(), 'English');
    userEvent.selectOptions(toLanguageElement(), 'Hindi');
    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    userEvent.selectOptions(toLanguageElement(), 'Bengali');
    await waitFor(() => expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguage.json'));
    await waitFor(() => expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument());
    await waitFor(() => expect(screen.queryByText('noDataMessageDashboard')).not.toBeInTheDocument());
    expect(screen.queryByText('languages')).not.toBeInTheDocument();
  });

  it('changing to language where data not available and clicking contribute now should display change user modal for new user', async () => {
    await setup();
    userEvent.selectOptions(fromLanguageElement(), 'English');
    userEvent.selectOptions(toLanguageElement(), 'Bengali');
    await waitFor(() => {
      expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
    });
    userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
    await waitFor(() => expect(screen.getByTestId('ChangeUserForm')).toBeInTheDocument());

    userEvent.click(screen.getByRole('button', { name: 'Close' }));

    await waitForElementToBeRemoved(() => screen.queryByTestId('ChangeUserModal'));
  });

  it('changing to language where data not available and clicking contribute now should redirect for existing user', async () => {
    when(localStorage.getItem)
      .calledWith('speakerDetails')
      .mockImplementation(
        () => '{"userName":"abc","motherTongue":"","age":"","gender":"","language":"English","toLanguage":""}'
      );
    when(localStorage.getItem)
      .calledWith('contributionLanguage')
      .mockImplementation(() => 'English');
    when(localStorage.getItem)
      .calledWith('translatedLanguage')
      .mockImplementation(() => 'Hindi');
    await setup();
    await waitFor(() => {
      expect(localStorage.getItem).toBeCalled();
    });
    userEvent.selectOptions(fromLanguageElement(), 'English');
    userEvent.selectOptions(toLanguageElement(), 'Bengali');
    await waitFor(() => {
      expect(screen.getByText('noDataMessageDashboard')).toBeInTheDocument();
    });
    userEvent.click(screen.getByRole('button', { name: 'contributeNow' }));
    await waitFor(() => expect(screen.queryByTestId('ChangeUserModal')).not.toBeInTheDocument());
    expect(localStorage.setItem).toBeCalledWith('contributionLanguage', 'English');
    expect(localStorage.setItem).toBeCalledWith('translatedLanguage', 'Bengali');
  });
});
Example #26
Source File: App.tsx    From yasd with MIT License 4 votes vote down vote up
App: React.FC = () => {
  const { t, i18n } = useTranslation()
  const [isNetworkModalOpen, setIsNetworkModalOpen] = useState(false)
  const location = useLocation()
  const history = useHistory()
  const profileDispatch = useProfileDispatch()
  const profile = useProfile()
  const [hasInit, setHasInit] = useState(false)
  const isCurrentVersionFetched = useRef(true)
  const platformVersion = usePlatformVersion()

  const onCloseApplication = useCallback(() => {
    if (isRunInSurge()) {
      store.remove(LastUsedProfile)
      store.remove(ExistingProfiles)
    }

    window.location.replace('/')
  }, [])

  useEffect(
    () => {
      const existingProfiles = store.get(ExistingProfiles)
      const lastId = store.get(LastUsedProfile)
      const result = find<Profile>(existingProfiles, { id: lastId })

      if (result) {
        profileDispatch({
          type: 'update',
          payload: result,
        })
      }

      setHasInit(true)
    },
    // eslint-disable-next-line
    [],
  )

  useEffect(() => {
    if (hasInit && !profile && location.pathname !== '/') {
      history.replace('/')
    }
  }, [hasInit, history, location.pathname, profile])

  useEffect(() => {
    ReactGA.pageview(location.pathname)
  }, [location.pathname])

  useEffect(() => {
    const language: string | null = store.get(LastUsedLanguage)

    if (language && language !== i18n.language) {
      i18n.changeLanguage(language)
    }
  }, [i18n])

  useEffect(() => {
    if (
      !profile?.platform ||
      !isCurrentVersionFetched.current ||
      location.pathname === '/'
    ) {
      return
    }

    httpClient
      .request({
        url: '/environment',
        method: 'GET',
      })
      .then((res) => {
        const currentPlatformVersion = res.headers['x-surge-version']

        if (currentPlatformVersion !== platformVersion) {
          profileDispatch({
            type: 'updatePlatformVersion',
            payload: {
              platformVersion: currentPlatformVersion,
            },
          })
        }

        isCurrentVersionFetched.current = false
      })
      .catch((err) => {
        console.error(err)
        toast.error(t('common.surge_too_old'))
      })
  }, [location, platformVersion, profile?.platform, profileDispatch, t])

  return (
    <SWRConfig
      value={{
        onError: (error) => {
          if (location.pathname !== '/') {
            if (!error.response && error.request) {
              // 无法连接服务器
              setIsNetworkModalOpen(true)
            }
          }
        },
        refreshWhenOffline: true,
      }}
    >
      <ScrollToTop />
      <ToastContainer />
      <NetworkErrorModal
        reloadButton={isRunInSurge()}
        isOpen={isNetworkModalOpen}
        onClose={onCloseApplication}
      />
      <NewVersionAlert />

      <PageLayout>
        <Switch>
          <Route exact path="/">
            {isRunInSurge() ? <SurgeLandingPage /> : <LandingPage />}
          </Route>
          <Route exact path="/home">
            <IndexPage />
          </Route>
          <Route exact path="/policies">
            <PoliciesPage />
          </Route>
          <Route exact path="/requests">
            <RequestsPage />
          </Route>
          <Route exact path="/traffic">
            <TrafficPage />
          </Route>
          <Route exact path="/modules">
            <ModulesPage />
          </Route>
          <Route exact path="/scripting">
            <ScriptingPage />
          </Route>
          <Route exact path="/scripting/evaluate">
            <EvaluatePage />
          </Route>
          <Route exact path="/dns">
            <DnsPage />
          </Route>
          <Route exact path="/devices">
            <DevicesPage />
          </Route>
          <Route exact path="/profiles/current">
            <ProfilePage />
          </Route>
          <Route path="*">
            <Redirect to="/" />
          </Route>
        </Switch>
      </PageLayout>
    </SWRConfig>
  )
}
Example #27
Source File: IndiaMapChart.test.tsx    From crowdsource-dataplatform with MIT License 4 votes vote down vote up
describe('IndiaMapChart with language', () => {
  const setup = async (
    type: 'asr' | 'ocr' | 'text' | 'parallel',
    language: string | undefined,
    responseData: any
  ) => {
    fetchMock
      .doMockOnceIf('/aggregated-json/cumulativeDataByLanguageAndState.json')
      .mockResponseOnce(JSON.stringify(responseData));
    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <IndiaMapChart type={type} language={language} />
      </SWRConfig>
    );
    await waitFor(() => {
      expect(fetchMock).toBeCalled();
    });
    return renderResult;
  };

  it('should fetch data from CumulativeDataByLanguageAndState for asr when language is specified', async () => {
    const data = [
      {
        state: 'Punjab',
        language: 'Hindi',
        total_speakers: 1,
        total_contributions: 0.001,
        total_validations: 1,
        total_contribution_count: 1,
        total_validation_count: 0,
        type: 'asr',
      },
    ];
    await setup('asr', 'Hindi', data);
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguageAndState.json');
    });
  });

  it('should set the default value for ocr when some params are missing from api', async () => {
    const data = [
      {
        state: 'Punjab',
        language: 'Hindi',
        total_speakers: 1,
        total_validations: 0,
        type: 'ocr',
      },
    ];
    await setup('ocr', 'Hindi', data);
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguageAndState.json');
    });
  });

  it('should set the default value for asr when some params are missing from api', async () => {
    const data = [
      {
        state: 'Punjab',
        language: 'Hindi',
        total_speakers: 1,
        total_validations: 0,
        total_contribution_count: 1,
        total_validation_count: 0,
        type: 'asr',
      },
    ];
    await setup('asr', 'Hindi', data);
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguageAndState.json');
    });
  });

  it('should set the default value for asr when language is not matching', async () => {
    const data = [
      {
        state: 'Punjab',
        language: 'English',
        total_speakers: 1,
        total_validations: 0,
        total_contribution_count: 1,
        total_validation_count: 0,
        type: 'asr',
      },
    ];
    await setup('asr', 'Hindi', data);
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeDataByLanguageAndState.json');
    });
  });
});
Example #28
Source File: ContributionStats.test.tsx    From crowdsource-dataplatform with MIT License 4 votes vote down vote up
describe('ContributionStats', () => {
  const setup = async (value?: any, showComponent?: boolean) => {
    fetchMock.doMockOnceIf('/aggregated-json/participationStats.json').mockResponseOnce(
      JSON.stringify([
        {
          count: '9',
          type: 'asr',
        },
        {
          count: '283',
          type: 'text',
        },
        {
          count: '53',
          type: 'ocr',
        },
        {
          count: null,
          type: 'parallel',
        },
      ])
    );

    fetchMock.doMockOnceIf('/aggregated-json/cumulativeCount.json').mockResponseOnce(
      JSON.stringify([
        {
          total_contribution_count: 45,
          total_contributions: 0.031,
          total_languages: 2,
          total_speakers: 11,
          total_validation_count: 8,
          total_validations: 0.002,
          type: 'ocr',
        },
        {
          total_contribution_count: 45,
          total_contributions: 0.031,
          total_languages: 2,
          total_speakers: 11,
          total_validation_count: 8,
          total_validations: 0.002,
          type: 'text',
        },
        {
          total_contribution_count: 45,
          total_contributions: 0.031,
          total_languages: 2,
          total_speakers: 11,
          total_validation_count: 8,
          total_validations: 0.002,
          type: 'asr',
        },
      ])
    );

    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <ContributionStats
          initiative={value}
          header="Header"
          subHeader="Sub Header"
          showComponent={showComponent}
        />
      </SWRConfig>
    );
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/participationStats.json');
    });
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith('/aggregated-json/cumulativeCount.json');
    });
    if (showComponent) {
      await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));
    }

    return renderResult;
  };

  async () => {
    verifyAxeTest(await setup('tts'));
  };

  it('should render the component and matches it against stored snapshot', async () => {
    const { asFragment } = await setup('tts', false);

    expect(asFragment()).toMatchSnapshot();
  });

  it('should render the result for initiative home page', async () => {
    await setup('tts', false);
    expect(screen.getByText('peopleParticipated')).toBeInTheDocument();
    expect(screen.getByText('durationTranscribed')).toBeInTheDocument();
    expect(screen.getByText('durationValidated')).toBeInTheDocument();
    expect(screen.getByText('languages')).toBeInTheDocument();
    expect(screen.getByText('2')).toBeInTheDocument();
    expect(screen.getByText('9')).toBeInTheDocument();
  });

  it('should render the result for translation initiative home page', async () => {
    await setup('asr', false);
    expect(screen.getByText('peopleParticipated')).toBeInTheDocument();
    expect(screen.getByText('durationRecorded')).toBeInTheDocument();
    expect(screen.getByText('durationValidated')).toBeInTheDocument();
    expect(screen.getByText('languages')).toBeInTheDocument();
    expect(screen.getByText('2')).toBeInTheDocument();
    expect(screen.getByText('283')).toBeInTheDocument();
  });
});
Example #29
Source File: AsrValidate.test.tsx    From crowdsource-dataplatform with MIT License 4 votes vote down vote up
describe('AsrValidate', () => {
  const storeUrl = '/store';
  const skipUrl = '/skip';
  const acceptUrl = '/validate/1717503/accept';
  const rejectUrl = '/validate/1717503/reject';
  const successResponse = { success: true };
  const locationInfo = {
    country: 'India',
    regionName: 'National Capital Territory of Delhi',
  };

  const speakerDetails = {
    userName: 'abc',
    motherTongue: '',
    age: '',
    gender: '',
    language: 'Hindi',
    toLanguage: '',
  };

  const contributionsData = JSON.stringify({
    data: [
      {
        contribution_id: 1717503,
        dataset_row_id: 1248712,
        sentence:
          'inbound/asr/English/newsonair.nic.in_09-08-2021_03-37/37_Regional-Shillong-English-0830-202131192011.wav',
        contribution: 'सोल को अगर आप नहीं देख सकते शीशा लगा करके आप जरूर देखिए',
        source_info: null,
      },
      {
        contribution_id: 1717502,
        dataset_row_id: 1248711,
        sentence:
          'inbound/asr/English/newsonair.nic.in_09-08-2021_03-37/37_Regional-Shillong-English-0830-202121195940.wav',
        contribution: 'नहीं देख सकते शीशा लगा करके आप जरूर देखिए',
        source_info: null,
      },
      {
        contribution_id: 1717501,
        dataset_row_id: 1248710,
        sentence:
          'inbound/asr/English/newsonair.nic.in_09-08-2021_03-37/37_Regional-Shillong-English-0830-202112711182.wav',
        contribution: 'आप जरूर देखिए',
        source_info: null,
      },
      {
        contribution_id: 1717497,
        dataset_row_id: 1248705,
        sentence:
          'inbound/asr/English/newsonair.nic.in_09-08-2021_03-37/37_Regional-Shillong-English-0830-202083094241.wav',
        contribution: 'देखिए',
        source_info: null,
      },
      {
        contribution_id: 1717496,
        dataset_row_id: 1248704,
        sentence:
          'inbound/asr/English/newsonair.nic.in_09-08-2021_03-37/37_Regional-Shillong-English-0830-20208293814.wav',
        contribution: 'देखिए',
        source_info: null,
      },
    ],
  });

  const setup = async (contributionsData: any) => {
    when(localStorage.getItem)
      .calledWith('contributionLanguage')
      .mockImplementation(() => 'Hindi');

    when(localStorage.getItem)
      .calledWith('locationInfo')
      .mockImplementation(() => JSON.stringify(locationInfo));

    when(localStorage.getItem)
      .calledWith('speakerDetails')
      .mockImplementation(() => JSON.stringify(speakerDetails));

    fetchMock
      .doMockOnceIf('/contributions/text?from=Hindi&to=&username=abc')
      .mockResponseOnce(contributionsData);
    fetchMock.doMockIf(storeUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(skipUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(acceptUrl).mockResponse(JSON.stringify(successResponse));
    fetchMock.doMockIf(rejectUrl).mockResponse(JSON.stringify(successResponse));
    const renderResult = render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <AsrValidate />
      </SWRConfig>
    );

    await waitForElementToBeRemoved(() => screen.queryAllByTestId('Loader'));

    return renderResult;
  };

  it('incorrect and correct button should be disabled initially', async () => {
    await setup(contributionsData);

    expect(screen.getByRole('button', { name: 'InCorrect Icon incorrect' })).toBeDisabled();
    expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeDisabled();
  });

  it('play button and skip button should be enabled initially', async () => {
    await setup(contributionsData);

    expect(screen.getByRole('button', { name: 'Play Icon play' })).toBeEnabled();
    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();
  });

  it('should show the thank you message when no data present', async () => {
    const result = JSON.stringify({ data: [] });
    await setup(result);

    await waitFor(() => {
      expect(screen.getByText('asrValidateNoDataThankYouMessage')).toBeInTheDocument();
    });
  });

  it('play button click should play audio and pause button should be enabled', async () => {
    await setup(contributionsData);

    expect(screen.getByRole('img', { name: 'Play Icon' })).toBeInTheDocument();

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    expect(screen.getByRole('img', { name: 'Pause Icon' })).toBeInTheDocument();
  });

  it('pause button click should pause audio and play button should be enabled', async () => {
    await setup(contributionsData);

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    expect(screen.getByRole('img', { name: 'Pause Icon' })).toBeInTheDocument();

    userEvent.click(screen.getByRole('img', { name: 'Pause Icon' }));

    expect(screen.getByRole('img', { name: 'Play Icon' })).toBeInTheDocument();
  });

  it('should enable incorrect and correct button when full audio is played', async () => {
    await setup(contributionsData);

    await waitFor(() =>
      expect(screen.getByRole('button', { name: 'InCorrect Icon incorrect' })).toBeDisabled()
    );
    await waitFor(() => expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeDisabled());

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() =>
      screen.getByTestId('asrValidateAudioElement').dispatchEvent(new window.Event('ended'))
    );
    await waitFor(() => expect(screen.getByRole('img', { name: 'Replay Icon' })).toBeInTheDocument());
    await waitFor(() =>
      expect(screen.getByRole('button', { name: 'InCorrect Icon incorrect' })).toBeEnabled()
    );
    await waitFor(() => expect(screen.getByRole('button', { name: 'Correct Icon correct' })).toBeEnabled());
  });

  it('should replay full audio is played and replay clicked', async () => {
    await setup(contributionsData);

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() =>
      screen.getByTestId('asrValidateAudioElement').dispatchEvent(new window.Event('ended'))
    );
    await waitFor(() => expect(screen.getByRole('img', { name: 'Replay Icon' })).toBeInTheDocument());
    userEvent.click(screen.getByRole('img', { name: 'Replay Icon' }));
    await waitFor(() => expect(screen.getByRole('img', { name: 'Pause Icon' })).toBeInTheDocument());
  });

  it('should test the skip functionality', async () => {
    const url = '/validate/1717503/skip';
    const successResponse = { message: 'Skipped successfully.', statusCode: 200 };

    await setup(contributionsData);
    fetchMock.doMockOnceIf(url).mockResponseOnce(JSON.stringify(successResponse));

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    userEvent.click(screen.getByRole('button', { name: 'skip' }));

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(url, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'text',
        }),
      });
    });
  });

  it('should test the correct functionality', async () => {
    const url = '/validate/1717503/accept';
    const successResponse = { message: 'Validate successfully.', statusCode: 200 };

    await setup(contributionsData);

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() =>
      screen.getByTestId('asrValidateAudioElement').dispatchEvent(new window.Event('ended'))
    );

    fetchMock.doMockOnceIf(url).mockResponseOnce(JSON.stringify(successResponse));

    expect(screen.getByRole('img', { name: 'Correct Icon' })).toBeEnabled();

    userEvent.click(screen.getByRole('img', { name: 'Correct Icon' }));

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(url, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'text',
        }),
      });
    });
  });

  it('should show the error popup when api throw the error and close modal on clicking button', async () => {
    const url = '/validate/1717503/accept';
    const errorResponse = new Error('Some error');
    await setup(contributionsData);
    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() =>
      screen.getByTestId('asrValidateAudioElement').dispatchEvent(new window.Event('ended'))
    );
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);
    expect(screen.getByRole('img', { name: 'Correct Icon' })).toBeEnabled();

    userEvent.click(screen.getByRole('img', { name: 'Correct Icon' }));
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(url, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'text',
        }),
      });
    });
    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });

    await waitFor(() => {
      expect(screen.queryByText('apiFailureError')).not.toBeInTheDocument();
    });
  });

  it('should show the error popup for 2nd sentence when api throw the error and modal should close on clicking button', async () => {
    const url = '/validate/1717503/skip';
    const errorResponse = new Error('Some error');
    await setup(contributionsData);
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    userEvent.click(screen.getByRole('button', { name: 'skip' }));
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(url, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'text',
        }),
      });
    });
    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });

    await waitFor(() => {
      expect(screen.queryByText('apiFailureError')).not.toBeInTheDocument();
    });
  });

  it('should test the incorrect functionality', async () => {
    const url = '/validate/1717503/reject';
    const successResponse = { message: 'Validate successfully.', statusCode: 200 };

    await setup(contributionsData);

    userEvent.click(screen.getByRole('img', { name: 'Play Icon' }));

    await waitFor(() =>
      screen.getByTestId('asrValidateAudioElement').dispatchEvent(new window.Event('ended'))
    );

    fetchMock.doMockOnceIf(url).mockResponseOnce(JSON.stringify(successResponse));

    expect(screen.getByRole('img', { name: 'InCorrect Icon' })).toBeEnabled();

    userEvent.click(screen.getByRole('img', { name: 'InCorrect Icon' }));

    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(url, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          country: 'India',
          state: 'National Capital Territory of Delhi',
          userName: 'abc',
          type: 'text',
        }),
      });
    });
  });

  it('should go to thank you page after 5 skip sentences', async () => {
    const url = '/validate/1717503/skip';
    const errorResponse = new Error('Some error');
    await setup(contributionsData);
    fetchMock.doMockOnceIf(url).mockRejectOnce(errorResponse);

    expect(screen.getByRole('button', { name: 'skip' })).toBeEnabled();

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'skip' }));
    });
    await waitFor(() => {
      expect(fetchMock).toBeCalledWith(url, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          device: 'android 11',
          browser: 'Chrome 13',
          userName: 'abc',
          fromLanguage: 'Hindi',
          sentenceId: 1248712,
          state: 'National Capital Territory of Delhi',
          country: 'India',
          type: 'text',
        }),
      });
    });
    await waitFor(() => {
      expect(screen.getByText('apiFailureError')).toBeInTheDocument();
    });

    await waitFor(() => {
      userEvent.click(screen.getByRole('button', { name: 'close' }));
    });
  });
});