Skip to content

Commit

Permalink
test: add tests do validators, mynetwork, informations and generators
Browse files Browse the repository at this point in the history
  • Loading branch information
gabriel-logan committed Sep 4, 2024
1 parent 249894e commit b547eef
Show file tree
Hide file tree
Showing 16 changed files with 723 additions and 36 deletions.
29 changes: 22 additions & 7 deletions jest/setupFiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,25 @@ jest.mock("react-native-base64", () => ({
encode: jest.fn(),
}));

jest.mock("react-native-vector-icons/MaterialCommunityIcons", () => "Icon");
jest.mock("react-native-vector-icons/FontAwesome5", () => "Icon");
jest.mock("react-native-vector-icons/FontAwesome", () => "Icon");
jest.mock("react-native-vector-icons/MaterialIcons", () => "Icon");
jest.mock("react-native-vector-icons/Feather", () => "Icon");
jest.mock("react-native-vector-icons/AntDesign", () => "Icon");
jest.mock("react-native-vector-icons/Entypo", () => "Icon");
jest.mock(
"react-native-vector-icons/MaterialCommunityIcons",
() => "MaterialCommunityIcons Icon"
);
jest.mock("react-native-vector-icons/FontAwesome5", () => "FontAwesome5 Icon");
jest.mock("react-native-vector-icons/FontAwesome", () => "FontAwesome Icon");
jest.mock(
"react-native-vector-icons/MaterialIcons",
() => "MaterialIcons Icon"
);
jest.mock("react-native-vector-icons/Feather", () => "Feather Icon");
jest.mock("react-native-vector-icons/AntDesign", () => "AntDesign Icon");
jest.mock("react-native-vector-icons/Entypo", () => "Entypo Icon");
jest.mock("react-native-vector-icons/Ionicons", () => "Ionicons Icon");

jest.mock("react-native-network-info", () => ({
NetworkInfo: {
getIPV4Address: jest.fn().mockResolvedValue("192.168.100.4"),
getGatewayIPAddress: jest.fn().mockResolvedValue("192.168.100.1"),
getSubnet: jest.fn().mockResolvedValue("255.25.255.0"),
},
}));
63 changes: 63 additions & 0 deletions src/pages/Informations/__tests__/Informations.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { fireEvent, render, screen } from "@testing-library/react-native";

import GeneralInfoPage from "..";

describe("Informations", () => {
it("should render correctly", () => {
render(<GeneralInfoPage />);

const title = screen.getByText(/Informações Gerais/i);

expect(title).toBeDefined();
});

it("should show contributors", () => {
render(<GeneralInfoPage />);

const contributors = screen.getByText(/Contribuidores/i);

expect(contributors).toBeDefined();
});

describe("Links buttons", () => {
it("should show and open github link", () => {
render(<GeneralInfoPage />);

const githubButton = screen.getByText(/Ir para o repositório github/i);

expect(githubButton).toBeDefined();

fireEvent.press(githubButton);
});

it("should show and open buy me a coffee link", () => {
render(<GeneralInfoPage />);

const coffeeButton = screen.getByText(/Buy me a coffee/i);

expect(coffeeButton).toBeDefined();

fireEvent.press(coffeeButton);
});

it("should show and open Privacy Policy link", () => {
render(<GeneralInfoPage />);

const privacyPolicyButton = screen.getByText(/Políticas de Privacidade/i);

expect(privacyPolicyButton).toBeDefined();

fireEvent.press(privacyPolicyButton);
});

it("should show and open Terms of Use link", () => {
render(<GeneralInfoPage />);

const termsButton = screen.getByText(/Termos de Uso/i);

expect(termsButton).toBeDefined();

fireEvent.press(termsButton);
});
});
});
73 changes: 73 additions & 0 deletions src/pages/MyNetwork/__tests__/MyNetwork.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { NavigationContainer } from "@react-navigation/native";
import { fireEvent, render, screen } from "@testing-library/react-native";
import axios from "axios";

import MyNetwork from "..";

describe("MyNetwork", () => {
it("should render correctly", async () => {
jest
.spyOn(axios, "get")
.mockResolvedValue({ data: { ip: "201.8.168.176" } });

render(
<NavigationContainer>
<MyNetwork />
</NavigationContainer>
);

const title = await screen.findByText(/Informações de Rede/i);

expect(title).toBeDefined();
});

it("should copy especific text to clipboard", async () => {
render(
<NavigationContainer>
<MyNetwork />
</NavigationContainer>
);

const buttons = await screen.findAllByLabelText(/buttonCopy/i);

expect(buttons).toHaveLength(4);

buttons.forEach((button) => {
fireEvent.press(button);
});
});

it("should show error message when get external ip fails", async () => {
jest.spyOn(axios, "get").mockResolvedValue({ data: undefined });

render(
<NavigationContainer>
<MyNetwork />
</NavigationContainer>
);

const error = await screen.findByText(
/Houve um problema não identificado na solicitação, tente novamente mais tarde/i
);

expect(error).toBeDefined();
});

it("should console.error when get external ip fails", async () => {
const consoleErrorSpy = jest
.spyOn(console, "error")
.mockImplementation(() => {});

jest.spyOn(axios, "get").mockRejectedValue(new Error("error"));

render(
<NavigationContainer>
<MyNetwork />
</NavigationContainer>
);

await new Promise((resolve) => setTimeout(resolve, 10));

consoleErrorSpy.mockRestore();
});
});
13 changes: 4 additions & 9 deletions src/pages/MyNetwork/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,6 @@ const MyNetwork = () => {
)
);
}

/**
* if (Platform.OS === 'android') {
const airplane = false;
setAirplaneMode(airplane);
} else {
setAirplaneMode(null);
}
*/
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
Expand All @@ -86,6 +77,7 @@ const MyNetwork = () => {
{geteway || t("Carregando...")}
</Text>
<TouchableOpacity
aria-label="buttonCopy"
onPress={() =>
copyToClipboard(geteway ? geteway : t("000.000.0.0"))
}
Expand All @@ -104,6 +96,7 @@ const MyNetwork = () => {
{ipAddress || t("Carregando...")}
</Text>
<TouchableOpacity
aria-label="buttonCopy"
onPress={() =>
copyToClipboard(ipAddress ? ipAddress : t("000.000.000.000"))
}
Expand All @@ -122,6 +115,7 @@ const MyNetwork = () => {
{subnet || t("Carregando...")}
</Text>
<TouchableOpacity
aria-label="buttonCopy"
onPress={() =>
copyToClipboard(subnet ? subnet : t("000.000.000.0"))
}
Expand All @@ -140,6 +134,7 @@ const MyNetwork = () => {
{ipAddressExternal || t("Carregando...")}
</Text>
<TouchableOpacity
aria-label="buttonCopy"
onPress={() =>
copyToClipboard(
ipAddressExternal ? ipAddressExternal : t("000.000.000.000")
Expand Down
15 changes: 7 additions & 8 deletions src/pages/generators/Cnpj/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,19 @@ export default function CnpjGeneratorPage() {
const [cnpjWithPeriod, setCnpjWithPeriod] = useState(false);

const formatCnpj = (Cnpj: string) => {
if (Cnpj && Cnpj.length === 14) {
return `${Cnpj.slice(0, 2)}.${Cnpj.slice(2, 5)}.${Cnpj.slice(
5,
8
)}/${Cnpj.slice(8, 12)}-${Cnpj.slice(12)}`;
}
return Cnpj;
return `${Cnpj.slice(0, 2)}.${Cnpj.slice(2, 5)}.${Cnpj.slice(
5,
8
)}/${Cnpj.slice(8, 12)}-${Cnpj.slice(12)}`;
};

const generateRandomCnpj = () => {
let randomCnpj: string;

do {
randomCnpj = generateRandomDigits();
} while (!cnpjIsValid(randomCnpj).isValid);

if (cnpjWithPeriod) {
setGeneratedCnpj(formatCnpj(randomCnpj));
} else {
Expand Down Expand Up @@ -110,7 +109,7 @@ export default function CnpjGeneratorPage() {
color="#007BFF"
/>
<View style={stylesWithTheme.copyButtonContainer}>
<TouchableOpacity onPress={copyToClipboard}>
<TouchableOpacity testID="buttonCopy" onPress={copyToClipboard}>
<FontAwesome name="copy" size={RFValue(32)} color="#007BFF" />
</TouchableOpacity>
</View>
Expand Down
99 changes: 99 additions & 0 deletions src/pages/generators/Cpf/__tests__/Cpf.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import { fireEvent, render, screen } from "@testing-library/react-native";

import CpfGeneratorPage from "..";

describe("Cpf Generator", () => {
beforeEach(() => {
jest.clearAllMocks();
AsyncStorage.clear();
});

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

it("should render correctly", () => {
render(<CpfGeneratorPage />);

const title = screen.getByText("Gerador de CPF");

expect(title).toBeDefined();
});

it("should generate a random CPF without punctuation", async () => {
render(<CpfGeneratorPage />);

const input = screen.getByPlaceholderText("Clique no botão abaixo");

expect(input).toBeDefined();

const button = screen.getByText("Gerar CPF");

expect(button).toBeDefined();

fireEvent.press(button);

expect(input.props.value).toMatch(/^\d{11}$/);
});

it("should change checkbox value", async () => {
render(<CpfGeneratorPage />);

const checkbox = screen.getByRole("checkbox");

fireEvent(checkbox, "onValueChange", true);

expect(checkbox.props.accessibilityState.checked).toBe(true);

fireEvent(checkbox, "onValueChange", false);

expect(checkbox.props.accessibilityState.checked).toBe(false);
});

it("should generate a random CPF with punctuation", async () => {
render(<CpfGeneratorPage />);

const input = screen.getByPlaceholderText("Clique no botão abaixo");

const checkbox = screen.getByRole("checkbox");

const button = screen.getByText("Gerar CPF");

fireEvent(checkbox, "onValueChange", true);

fireEvent.press(button);

expect(input.props.value).toMatch(/^\d{3}\.\d{3}\.\d{3}-\d{2}$/);
});

it("should copy generated CPF to clipboard", async () => {
render(<CpfGeneratorPage />);

const buttonCopy = screen.getByTestId("buttonCopy");

const button = screen.getByText("Gerar CPF");

fireEvent.press(button);

fireEvent.press(buttonCopy);
});

it("should not copy if there is no generated CPF", async () => {
render(<CpfGeneratorPage />);

const buttonCopy = screen.getByTestId("buttonCopy");

fireEvent.press(buttonCopy);
});

it("should load checkbox value from AsyncStorage", async () => {
(AsyncStorage.getItem as jest.Mock).mockResolvedValueOnce("true");

render(<CpfGeneratorPage />);

const checkbox = await screen.findByRole("checkbox");

expect(checkbox.props.accessibilityState.checked).toBe(true);
});
});
13 changes: 5 additions & 8 deletions src/pages/generators/Cpf/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,10 @@ export default function CpfGeneratorPage() {
const [cpfWithPeriod, setCpfWithPeriod] = useState(false);

const formatCpf = (cpf: string) => {
if (cpf && cpf.length === 11) {
return `${cpf.slice(0, 3)}.${cpf.slice(3, 6)}.${cpf.slice(
6,
9
)}-${cpf.slice(9)}`;
}
return cpf;
return `${cpf.slice(0, 3)}.${cpf.slice(3, 6)}.${cpf.slice(
6,
9
)}-${cpf.slice(9)}`;
};

const generateRandomCpf = () => {
Expand Down Expand Up @@ -103,7 +100,7 @@ export default function CpfGeneratorPage() {
color="#007BFF"
/>
<View style={stylesWithTheme.copyButtonContainer}>
<TouchableOpacity onPress={copyToClipboard}>
<TouchableOpacity testID="buttonCopy" onPress={copyToClipboard}>
<FontAwesome name="copy" size={RFValue(32)} color="#007BFF" />
</TouchableOpacity>
</View>
Expand Down
Loading

0 comments on commit b547eef

Please sign in to comment.