Add App.test.tsx

This commit is contained in:
0x1eef 2023-09-29 15:24:08 -03:00
parent d06d7d4389
commit e498c5b6e2
4 changed files with 78 additions and 2 deletions

View file

@ -3,7 +3,7 @@ import React from "react";
export function ErrorRenderer({ error }: {error: Error}) {
const t = chrome.i18n.getMessage;
return (
<div className="error">
<div data-testid="error" className="error">
<span>{t("error")}</span>:
<span>&nbsp;{error.message}</span>
</div>

View file

@ -13,7 +13,7 @@ export function ResponseRenderer({ response }: {response: TResponse}) {
}
return (
<div className="response">
<div data-testid="response" className="response">
<div className="row">
<div>{t("ip_address")}</div>
<div>{response.IPAddress}</div>

47
test/App.test.tsx Normal file
View file

@ -0,0 +1,47 @@
import React from "react";
import '@testing-library/jest-dom'
import { render, screen, act, waitFor } from "@testing-library/react";
import { App } from "~/components/App";
import { getMessage } from "./mocks/chrome.i18n";
import { success, error, loading } from "./mocks/fetch";
describe("App.tsx", () => {
beforeEach(() => {
const chrome: any = {i18n: {getMessage}};
global.chrome = chrome;
});
afterEach(() => {
global.chrome = undefined;
});
describe("when the request is loading", () => {
beforeEach(() => { global.fetch = loading });
afterEach(() => { global.fetch = undefined });
test("loading text is rendered", () => {
render(<App/>);
expect(screen.getByText("Loading...")).toBeInTheDocument();
})
});
describe("when the request is a success", () => {
beforeEach(() => { global.fetch = success });
afterEach(() => { global.fetch = undefined });
test("response is rendered", async () => {
await act(() => render(<App/>));
expect(screen.getByTestId("response")).toBeInTheDocument();
});
});
describe("when the request throws an error", () => {
beforeEach(() => { global.fetch = error });
afterEach(() => { global.fetch = undefined });
test("error is rendered", async () => {
await act(() => render(<App/>));
expect(screen.getByTestId("error")).toBeInTheDocument();
});
});
});

29
test/mocks/fetch.ts Normal file
View file

@ -0,0 +1,29 @@
import {TServerResponse} from "~/lib/response";
export function success(_path: RequestInfo | URL, _options?: RequestInit) {
const json = () => (
new Promise<TServerResponse>((resolve) => (
resolve({
YourFuckingIPAddress: "127.0.0.1",
YourFuckingISP: "FooBar Ltd",
YourFuckingCity: "Foo City",
YourFuckingCountry: "United States of FooBar",
YourFuckingTorExit: false
})
)
))
return new Promise<any>((resolve) => {
resolve({status: 200, json});
});
}
export function error(_path: RequestInfo | URL, _options?: RequestInit) {
return new Promise<any>(() => {
throw new Error("Request error");
})
};
export function loading(_path: RequestInfo | URL, _options?: RequestInit) {
return new Promise<any>(() => null);
}