Blog: Nowe responsywne menu
Opublikowano: 22.09.2023 - tagi: Blog Menu Responsywność
Wrzuciłem nowe responsywne menu (wg mnie lepsze):

Opublikowano: 22.09.2023 - tagi: Blog Menu Responsywność
Wrzuciłem nowe responsywne menu (wg mnie lepsze):
Opublikowano: 21.09.2023 - tagi: JavaScript React Testowanie Test Komponent Formularz Kontrolka Lista
Do pracy z listami biblioteka user-event udostępnia dwie funkcje: selectOptions i deselectOptions.
W tym wpisie do testów posłużę się takim przykładem:
import {useState} from "react";
const mealMap = {
1: "Kebab",
2: "Salad",
3: "Soup"
}
export function MyComponent({mealId}) {
const [meal, setMeal] = useState(mealId);
const onListChange = e => {
setMeal(e.target.value);
}
return (
<>
{ meal &&
<div>
Here we go! Your meal: {mealMap[meal]}
</div>
}
<div>
<label htmlFor="meal">Choose your meal:</label>
<select id="meal" onChange={onListChange}>
<option value=""></option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
</div>
</>
)
}
Test:
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {MyComponent} from "./MyComponent";
const { getByText, getByLabelText } = screen;
test('should display meal chosen by user', async () => {
// given
render(<MyComponent />);
const select = getByLabelText('Choose your meal:');
// when
await userEvent.selectOptions(select, ['1'])
// then
expect(getByText('Here we go! Your meal: Kebab')).toBeInTheDocument();
});
Jeśli masz listę jednego wyboru, to jak można przetestować odznaczanie opcji? Musisz zrobić dwie rzeczy.
Do swojej listy dodaj pustą opcję:
<option value=""></option>
Następnie za pomocą metody selectOptions przekaż pusty string.
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {MyComponent} from "./MyComponent";
const { queryByText, getByLabelText } = screen;
test('should deselect meal', async () => {
// given
render(<MyComponent mealId='3' />);
const select = getByLabelText('Choose your meal:');
// when
await userEvent.selectOptions(select, [''])
// then
expect(queryByText('Here we go! Your meal: Soup')).not.toBeInTheDocument();
});
Za pomocą atrybutu multiple sprawisz, że użytkownik będzie mógł wybrać więcej niż jedną opcję.
Komponent:
export function MyComponent() {
return (
<>
<label htmlFor="meal">Choose your meal:</label>
<select id="meal" multiple>
<option value="1">Kebab</option>
<option value="2">Salad</option>
<option value="3">Soup</option>
</select>
</>
)
}
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {MyComponent} from "./MyComponent";
const { getByText, getByLabelText } = screen;
test('should choose many meals', async () => {
// given
render(<MyComponent />)
const select = getByLabelText('Choose your meal:');
// when
await userEvent.selectOptions(select, ['2', '3'])
// then
expect(getByText('Salad').selected).toBeTruthy();
expect(getByText('Soup').selected).toBeTruthy();
expect(getByText('Kebab').selected).toBeFalsy();
});
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {MyComponent} from "./MyComponent";
const { getByText, getByLabelText } = screen;
test('should deselect many meals', async () => {
// given
render(<MyComponent />)
const select = getByLabelText('Choose your meal:');
await userEvent.selectOptions(select, ['1', '2', '3']);
// when
await userEvent.deselectOptions(select, ['1', '3'])
// then
expect(getByText('Salad').selected).toBeTruthy();
expect(getByText('Soup').selected).toBeFalsy();
expect(getByText('Kebab').selected).toBeFalsy();
});
Struktury pozwalają na organizację danych i dzięki temu łatwiejsze ich zarządzanie.
Składnia prezentuje się następująco:
struct SomeStruct {
...
}
Żeby stworzyć strukturę, użyj słowa kluczowego struct, a następnie podajesz jej nazwę.
W ciele struktury określasz jej właściwości. Możesz też dodać do niej funkcje. W kontekście struktura funkcje nazywane są metodami.
struct Product {
var name: String = ""
var price: Float = 0.0
func describe() {
print("Product name: \(name) and price is: \(price)")
}
}
Tworzenie instancji struktury wygląda tak:
var product = Product()
product.name = "Some product"
product.price = 9.99
product.describe() // Product name: Some product and price is: 9.99
Można też określić wartości struktury w momencie jej tworzenia:
var product = Product(name: "Some product", price: 9.99)
product.describe() // Product name: Some product and price is: 9.99
Uwaga: ważna jest kolejność parametrów. Jeśli pierwszą właściwością w strukturze jest: A, a potem B podczas tworzenia instancji struktury musisz podać wartości, w takiej kolejności.
Czyli w przypadku Product nie możesz napisać tak:
var product = Product(price: 9.99, name: "Some product") // błąd!
Możesz do tworzenia instancji struktury także użyć metody init:
struct Product {
var name: String
var price: Float
init(name: String, price: Float) {
self.name = name
self.price = price
}
func describe() {
print("Product name: \(name) and price is: \(price)")
}
}
Dzięki tej metodzie sam możesz określić kolejność podawanych argumentów przy tworzeniu instancji struktury.
Jeśli potrzebujesz dodać do struktury metodę, która zmieni swój stan, nie możesz napisać tego w taki sposób:
struct Cart {
var products: [Product] = []
func addProduct(_ product: Product) {
products.append(product)
}
}
var product = Product(name: "Some product", price: 19.99)
var cart = Cart()
cart.addProduct(product) // błąd!
Dlaczego? W Swift struktury są niezmienne ang.: immutable. Oznacza to, że z poziomu struktury nie możesz zmienić jej stanu. No nie do końca.
Wystarczy, że do danej metody dodasz słowo kluczowe mutating:
struct Cart {
var products: [Product] = []
mutating func addProduct(_ product: Product) {
products.append(product)
}
}
var product = Product(name: "Some product", price: 19.99)
var cart = Cart()
cart.addProduct(product)
print(cart.products.count) // 1
Jeśli instancję struktury określisz za pomocą let:
let product = Product(name: "Some product", price: 19.99)
nie możesz napisać tak:
product.name = "Extra product" // błąd!
Za pomocą let mówisz Swift, że stan obiektu nie może się zmienić.
Opublikowano: 12.09.2023 - tagi: JavaScript React Testowanie Test Komponent Formularz Kontrolka
Załóżmy, że testujesz przypadek: formularz jest wypełniony danymi i potrzebujesz przed sprawdzeniem testu, wyczyścić daną kontrolkę. Jak to zrobić?
Komponent:
import {useState} from "react";
export function MyComponent({ userName }: { userName: string}) {
const [name, setName] = useState(userName);
const onInputChange = e => {
setName(e.target.value);
}
return (
<>
{ name &&
<div>
Hello {name}! How are you?
</div>
}
<div>
<label htmlFor="name">Your name:</label>
<input value={name} id="name" name="name" onChange={onInputChange} />
</div>
</>
)
}
Test:
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {MyComponent} from "./MyComponent";
test('should edit user name', async () => {
// given
render(<MyComponent userName="Iwona" />);
const input = getByDisplayValue('Iwona');
await userEvent.clear(input);
// when
await userEvent.type(input, 'Adam');
// then
expect(getByText('Hello Adam! How are you?')).toBeInTheDocument();
});
Na starcie przekazywana jest wartość do komponentu, która jest przypisana jest do kontrolki.
Żeby wprowadzić nową wartość, musimy kontrolkę wyczyścić. Robi się to za pomocą metody: clear z biblioteki: user-event. Jeśli zakomentujesz tę linijkę wartość kontrolki po wywołaniu metody: type będzie: "IwonaAdam".
Opublikowano: 09.09.2023 - tagi: React UI Rozmiar Formularz Kontrolka
Żeby ustawić daną kontrolką na pełną szerokość, wystarczy ustawić jej atrybut: fullWidth.
Przykład:
import TextField from '@mui/material/TextField';
<TextField fullWidth variant="outlined" />