Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created home page game section tests #84

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/gameshare/lib/services/api_requests.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Future<List<Game>> fetchGames(http.Client client,

if (res.statusCode == 200) {
return [
for (int i = 0; i < decodedJson.length; i++)
for (int i = 0; i < decodedJson['results'].length; i++)
Game.fromJson(decodedJson['results'], i)
];
}
Expand Down
13 changes: 10 additions & 3 deletions app/gameshare/lib/view/components/game_card.dart
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:gameshare/consts/app_colors.dart';
import 'package:gameshare/view/screens/game.dart';
import '../../model/game.dart';

class GameCard extends StatelessWidget {
const GameCard({
GameCard({
super.key,
required this.game,
this.mockCache
});

final Game game;
BaseCacheManager? mockCache;

@override
Widget build(BuildContext context) {
Expand All @@ -37,7 +40,7 @@ class GameCard extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
GameCardImage(game: game),
GameCardImage(game: game, mockCache: mockCache),
const SizedBox(height: 10),
Row(
children: [
Expand Down Expand Up @@ -180,12 +183,14 @@ class GameCardRating extends StatelessWidget {
}

class GameCardImage extends StatelessWidget {
const GameCardImage({
GameCardImage({
super.key,
required this.game,
this.mockCache,
});

final Game game;
BaseCacheManager? mockCache;

@override
Widget build(BuildContext context) {
Expand All @@ -195,6 +200,8 @@ class GameCardImage extends StatelessWidget {
fit: BoxFit.fill,
child: CachedNetworkImage(
imageUrl: game.image,
cacheManager: mockCache,
fadeInDuration: Duration(milliseconds: 200),
errorWidget: (context, url, error) => Image.network(
'https://www.slntechnologies.com/wp-content/uploads/2017/08/ef3-placeholder-image.jpg'),
),
Expand Down
2 changes: 1 addition & 1 deletion app/gameshare/lib/view/components/nav_bar.dart
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class _NavBarState extends State<NavBar> {
Navigator.pushReplacement(
context,
PageRouteBuilder(
pageBuilder: (_, __, ____) => const HomePage(),
pageBuilder: (_, __, ____) => HomePage(),
transitionDuration: const Duration(seconds: 0),
),
);
Expand Down
10 changes: 8 additions & 2 deletions app/gameshare/lib/view/components/scrollable_game_list.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:http/http.dart';
import '../../model/game.dart';
import '../../services/api_requests.dart';
import 'api_error_message.dart';
Expand All @@ -11,9 +13,13 @@ class ScrollableGameList extends StatefulWidget {
int? pageSize;
String? searchQuery;
List<String>? genres;
BaseCacheManager? mockCache;
Client? client;

ScrollableGameList({
Key? key,
this.mockCache,
this.client,
required this.scrollHorizontally,
this.page,
this.pageSize,
Expand All @@ -29,7 +35,7 @@ class _ScrollableGameListState extends State<ScrollableGameList> {
late Future<List<Game>> futureGames;

void fetch() {
futureGames = fetchGames(IOClient(),
futureGames = fetchGames(widget.client ?? IOClient(),
page: widget.page,
pageSize: widget.pageSize,
searchQuery: widget.searchQuery,
Expand All @@ -50,7 +56,7 @@ class _ScrollableGameListState extends State<ScrollableGameList> {
scrollDirection:
widget.scrollHorizontally ? Axis.horizontal : Axis.vertical,
children: [
for (var game in snapshot.data!) GameCard(game: game),
for (var game in snapshot.data!) GameCard(game: game, mockCache: widget.mockCache,),
],
);
}
Expand Down
19 changes: 16 additions & 3 deletions app/gameshare/lib/view/screens/home.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:gameshare/services/api_requests.dart';
import 'package:gameshare/view/components/circular_progress.dart';
import 'package:gameshare/view/components/top_bar.dart';
import 'package:http/http.dart';
import '../../model/genre.dart';
import '../../services/providers/scroll_provider.dart';
import '../components/api_error_message.dart';
Expand All @@ -11,7 +13,14 @@ import '../components/section_title.dart';
import 'package:http/io_client.dart';

class HomePage extends StatefulWidget {
const HomePage({super.key});
HomePage({
super.key,
this.mockCache,
this.client,
});

BaseCacheManager? mockCache;
Client? client;

@override
State<HomePage> createState() => _HomePageState();
Expand All @@ -23,7 +32,7 @@ class _HomePageState extends State<HomePage> {
@override
void initState() {
super.initState();
allGenres = fetchGenres(IOClient());
allGenres = fetchGenres(widget.client ?? IOClient());
}

@override
Expand All @@ -50,7 +59,11 @@ class _HomePageState extends State<HomePage> {
height: 300,
child: ScrollableGameList(
scrollHorizontally: true,
genres: [genre.slug])),
genres: [genre.slug],
mockCache: widget.mockCache,
client: widget.client,
)
),
],
),
],
Expand Down
2 changes: 1 addition & 1 deletion app/gameshare/lib/view/screens/login.dart
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class _LoginPageState extends State<LoginPage> {
Navigator.push(
context,
PageRouteBuilder(
pageBuilder: (_, __, ____) => const HomePage(),
pageBuilder: (_, __, ____) => HomePage(),
transitionDuration: const Duration(seconds: 0),
),
);
Expand Down
2 changes: 1 addition & 1 deletion app/gameshare/lib/view/screens/register.dart
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class _RegisterPageState extends State<RegisterPage> {
Navigator.push(
context,
PageRouteBuilder(
pageBuilder: (_, __, ____) => const HomePage(),
pageBuilder: (_, __, ____) => HomePage(),
transitionDuration: const Duration(seconds: 0),
),
);
Expand Down
2 changes: 2 additions & 0 deletions app/gameshare/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ dependencies:
firebase_auth_mocks: ^0.11.0
flutter_driver:
sdk: flutter
flutter_cache_manager: ^3.3.0
file: ^6.1.4



Expand Down
Binary file added app/gameshare/test/assets/mock_image.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions app/gameshare/test/mocks.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import 'package:file/local.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:mockito/mockito.dart';
import 'package:gameshare/services/auth.dart';
import 'package:firebase_auth_mocks/firebase_auth_mocks.dart';
import 'package:file/file.dart';

class MockAuth extends Mock implements Auth {
final MockFirebaseAuth auth;
Expand All @@ -22,3 +25,24 @@ class MockAuth extends Mock implements Auth {
return false;
}
}

class MockCacheManager extends Mock implements BaseCacheManager {
static const fileSystem = LocalFileSystem();
@override
Stream<FileResponse> getFileStream(
String url, {
String? key,
Map<String, String>? headers,
bool? withProgress,
}) async* {

final file = fileSystem.file('mock_image.jpg');

yield FileInfo(
file, // Path to the asset
FileSource.Cache, // Simulate a cache hit
DateTime(2050), // Very long validity
url, // Source url
);
}
}
83 changes: 83 additions & 0 deletions app/gameshare/test/view/components/game_card_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gameshare/consts/platform_icons.dart';
import 'package:gameshare/model/game.dart';
import 'package:gameshare/view/components/game_card.dart';

void main() {
late GameCard regularGameCard, moreThanThreePlatforms;

setUp(() {
regularGameCard = GameCard(
game: Game(1, 'an-image', ['playstation4', 'pc'], 'Nice game'),
);

moreThanThreePlatforms = GameCard(
game: Game(
2, 'an-image', ['playstation4', 'pc', 'android', 'wii'], 'Nice game'),
);
});

group('Test widgets on Game Card', () {
testWidgets('Game Card should always have its game title, image and rating',
(WidgetTester widgetTester) async {
await widgetTester
.pumpWidget(MaterialApp(home: Scaffold(body: regularGameCard)));

expect(find.byType(GameCardImage), findsOneWidget);
expect(find.byType(GameCardName), findsOneWidget);
expect(find.byType(GameCardRating), findsOneWidget);
});

testWidgets(
'Game Card should not display MorePlatformsWidget with 3 or different platforms',
(WidgetTester widgetTester) async {
await widgetTester
.pumpWidget(MaterialApp(home: Scaffold(body: regularGameCard)));

expect(find.byType(MorePlatformsNumber), findsNothing);
});

testWidgets(
'Game Card should display MorePlatformsWidget with 3 or more different platforms',
(WidgetTester widgetTester) async {
await widgetTester.pumpWidget(
MaterialApp(home: Scaffold(body: moreThanThreePlatforms)));

expect(find.byType(GameCardImage), findsOneWidget);
expect(find.byType(GameCardName), findsOneWidget);
expect(find.byType(GameCardRating), findsOneWidget);
expect(find.byType(MorePlatformsNumber), findsOneWidget);
});
});

group('Test if the widgets show the right information', () {
// TODO: Test will need changes when the rating of each game is updated
testWidgets(
'Game card with 3 or less platforms should find game title, rating and each platform',
(WidgetTester widgetTester) async {
await widgetTester
.pumpWidget(MaterialApp(home: Scaffold(body: regularGameCard)));

expect(find.text('Nice game'), findsOneWidget);
expect(find.text('0.00'), findsOneWidget);
expect(find.byIcon(PlatformIcons.playstation), findsOneWidget);
expect(find.byIcon(PlatformIcons.pc), findsOneWidget);
});

testWidgets(
'Game card with more than 3 platforms should find game title, rating the first three platforms and a number with the additional number of platforms',
(WidgetTester widgetTester) async {
await widgetTester.pumpWidget(
MaterialApp(home: Scaffold(body: moreThanThreePlatforms)));

expect(find.widgetWithText(GameCardName, 'Nice game'), findsOneWidget);
expect(find.widgetWithText(GameCardRating, '0.00'), findsOneWidget);
expect(find.byIcon(PlatformIcons.playstation), findsOneWidget);
expect(find.byIcon(PlatformIcons.pc), findsOneWidget);
expect(find.byIcon(PlatformIcons.android), findsOneWidget);
expect(find.byIcon(PlatformIcons.nintendo), findsNothing);
expect(find.widgetWithText(MorePlatformsNumber, '+1'), findsOneWidget);
});
});
}
63 changes: 63 additions & 0 deletions app/gameshare/test/view/screens/home_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gameshare/view/components/scrollable_game_list.dart';
import 'package:gameshare/view/screens/home.dart';
import '../../mocks.dart';
import '../../services/api_requests_test.mocks.dart';
import 'package:http/http.dart';
import 'package:mockito/mockito.dart';

Future<void> main() async {
TestWidgetsFlutterBinding.ensureInitialized();
MockClient client = MockClient();
await dotenv.load(fileName: ".env");
String gamesUrl =
'${dotenv.env['API_URL_BASE']}/games?key=${dotenv.env['FLUTTER_APP_API_KEY']}';
String genresUrl =
'${dotenv.env['API_URL_BASE']}/genres?key=${dotenv.env['FLUTTER_APP_API_KEY']}';

testWidgets('There should be a row for each game genre in the home page', (widgetTester) async {
when(client.get(Uri.parse(genresUrl))).thenAnswer((_) async => Response(
'{"results": ['
'{"name": "Action", "slug": "action"},'
'{"name": "Puzzle", "slug": "puzzle"}'
']}',
200));

when(client.get(Uri.parse('$gamesUrl&page=1&page_size=1&genres=action')))
.thenAnswer((_) async => Response(
'{'
'"results": [{'
'"id": 1, '
'"background_image": "TheImage", '
'"platforms": [{"platform": {"name": "Playstation 4", "slug": "playstation4"}}], '
'"name": "TheGame"'
'},'
'{'
'"id": 2, '
'"background_image: "AnotherImage",'
'"platforms": [{"platform": {"name": "Playstation 4", "slug": "playstation4"}}], '
'"name": "AnotherGame"'
'}]}',
200));

when(client.get(Uri.parse('$gamesUrl&page=1&page_size=1&genres=puzzle')))
.thenAnswer((_) async => Response(
'{'
'"results": [{'
'"id": 3, '
'"background_image": "PuzzleImage", '
'"platforms": [{"platform": {"name": "Playstation 4", "slug": "playstation4"}}], '
'"name": "PuzzleGame"'
'}]}',
200));
Widget test = MaterialApp(home: HomePage(client: client,));
await widgetTester.pumpWidget(test);
await widgetTester.pumpFrames(test, const Duration(seconds: 10));

expect(find.byType(ScrollableGameList), findsNWidgets(2));
expect(find.text('Action'), findsOneWidget);
expect(find.text('Puzzle'), findsOneWidget);
});
}
1 change: 0 additions & 1 deletion app/gameshare/test/view/screens/login_test.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:firebase_auth_mocks/firebase_auth_mocks.dart';
Expand Down