use crate::{
context::{use_context, use_context_provider},
test_utils::with_component_id,
};
#[derive(Clone, Debug, PartialEq)]
struct TestUser {
name: String,
role: String,
}
#[derive(Clone, Debug, PartialEq)]
struct TestTheme {
color: String,
font: String,
}
#[test]
fn test_context_provider_and_use() {
with_component_id("ContextProviderComponent", |_ctx| {
let user = use_context_provider(|| TestUser {
name: "Test User".to_string(),
role: "Admin".to_string(),
});
assert_eq!(
user,
TestUser {
name: "Test User".to_string(),
role: "Admin".to_string(),
}
);
with_component_id("ContextConsumerComponent", |_ctx| {
let user = use_context::<TestUser>();
assert_eq!(
user,
TestUser {
name: "Test User".to_string(),
role: "Admin".to_string(),
}
);
});
});
}
#[test]
fn test_multiple_context_types() {
with_component_id("ContextProviderComponent", |_ctx| {
let user = use_context_provider(|| TestUser {
name: "Test User".to_string(),
role: "Admin".to_string(),
});
let theme = use_context_provider(|| TestTheme {
color: "Dark".to_string(),
font: "Sans".to_string(),
});
assert_eq!(
user,
TestUser {
name: "Test User".to_string(),
role: "Admin".to_string(),
}
);
assert_eq!(
theme,
TestTheme {
color: "Dark".to_string(),
font: "Sans".to_string(),
}
);
with_component_id("ContextConsumerComponent", |_ctx| {
let user = use_context::<TestUser>();
let theme = use_context::<TestTheme>();
assert_eq!(
user,
TestUser {
name: "Test User".to_string(),
role: "Admin".to_string(),
}
);
assert_eq!(
theme,
TestTheme {
color: "Dark".to_string(),
font: "Sans".to_string(),
}
);
});
});
}
#[test]
fn test_nested_context_providers() {
with_component_id("ContextProviderComponent", |_ctx| {
let outer_theme = use_context_provider(|| TestTheme {
color: "Light".to_string(),
font: "Serif".to_string(),
});
assert_eq!(
outer_theme,
TestTheme {
color: "Light".to_string(),
font: "Serif".to_string(),
}
);
let theme = use_context::<TestTheme>();
assert_eq!(
theme,
TestTheme {
color: "Light".to_string(),
font: "Serif".to_string(),
}
);
});
with_component_id("ContextProviderComponent", |_ctx| {
let inner_theme = use_context_provider(|| TestTheme {
color: "Dark".to_string(),
font: "Sans".to_string(),
});
assert_eq!(
inner_theme,
TestTheme {
color: "Dark".to_string(),
font: "Sans".to_string(),
}
);
let theme = use_context::<TestTheme>();
assert_eq!(
theme,
TestTheme {
color: "Dark".to_string(),
font: "Sans".to_string(),
}
);
});
with_component_id("ContextProviderComponent", |_ctx| {
let grandchild_theme = use_context_provider(|| TestTheme {
color: "Blue".to_string(),
font: "Monospace".to_string(),
});
assert_eq!(
grandchild_theme,
TestTheme {
color: "Blue".to_string(),
font: "Monospace".to_string(),
}
);
let theme = use_context::<TestTheme>();
assert_eq!(
theme,
TestTheme {
color: "Blue".to_string(),
font: "Monospace".to_string(),
}
);
});
}