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

Chapter 4 #3

Open
wants to merge 4 commits into
base: chapter-3
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
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@
"preview": "vite preview",
"deploy": "yarn build && firebase deploy --except functions",
"test": "vitest run",
"emulators:start:firestore": "firebase emulators:start --project testable-firebase-test --only firestore"
"emulators:start:firestore": "firebase emulators:start --project testable-firebase-test --only firestore",
"emulators:test": "firebase emulators:exec --project testable-firebase-test --only firestore 'yarn test'"
},
"dependencies": {
"date-fns": "^2.30.0",
"firebase": "^10.1.0",
"lodash-es": "^4.17.21",
"react": "^18.2.0",
Expand Down
42 changes: 0 additions & 42 deletions src/App.css

This file was deleted.

35 changes: 0 additions & 35 deletions src/App.tsx

This file was deleted.

1 change: 0 additions & 1 deletion src/assets/react.svg

This file was deleted.

7 changes: 7 additions & 0 deletions src/components/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const App = () => {
return (
<div>
<h1>Sample Chat App</h1>
</div>
);
};
23 changes: 23 additions & 0 deletions src/components/Message.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { format } from 'date-fns';
import { useUsers } from '@/contexts/UsersContext';
import { LoadingScreen } from './LoadingScreen';
import { Message as MessageType } from '@/types/message';
import nonameIcon from '@/images/noname.png';

export const Message = ({ message }: { message: MessageType }) => {
const { usersById, loading } = useUsers();
const sender = usersById[message.senderId];

if (loading) return <LoadingScreen />;

return (
<div>
<div>
<img src={sender?.photoUrl || nonameIcon} />
<span>{sender?.name || '名無しさん'}</span>
<span>{format(message.createdAt.toDate(), 'yyyy-MM-dd HH:mm')}</span>
</div>
<p>{message.content}</p>
</div>
);
};
29 changes: 29 additions & 0 deletions src/contexts/UsersContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { ReactNode, createContext, useContext, useMemo } from 'react';
import { keyBy } from 'lodash-es';
import { User } from '@/types/user';
import { useCollectionData } from '@/hooks/useCollectionData';
import { usersRef } from '@/lib/user';

type UsersContextValue = {
users: User[];
usersById: { [id: string]: User };
loading: boolean;
};

export const UsersContext = createContext<UsersContextValue>({
users: [],
usersById: {},
loading: true,
});

export const UsersProvider = ({ children }: { children: ReactNode }) => {
const [users, loading] = useCollectionData<User>(usersRef());
const usersById = useMemo(() => keyBy(users, 'id'), [users]);

return <UsersContext.Provider value={{ users: users || [], usersById, loading }}>{children}</UsersContext.Provider>;
};

export const useUsers = () => {
const { users, usersById, loading } = useContext(UsersContext);
return { users, usersById, loading };
};
10 changes: 10 additions & 0 deletions src/hooks/useCollectionData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { useMemo } from 'react';
import { Query } from 'firebase/firestore';
import { useCollectionData as _useCollectionData } from 'react-firebase-hooks/firestore';

export const useCollectionData = <T>(_query: Query<T>, deps: unknown[] = []) => {
const query = useMemo(() => _query, deps);
return _useCollectionData(query, {
snapshotOptions: { serverTimestamps: 'estimate' },
});
};
69 changes: 0 additions & 69 deletions src/index.css

This file was deleted.

2 changes: 1 addition & 1 deletion src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import { App } from './components/App';
import './index.css';
import '@/lib/firebase';

Expand Down
11 changes: 11 additions & 0 deletions test/components/App.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { render, cleanup, screen } from '@testing-library/react';
import { App } from '@/components/App';

describe('App', () => {
afterEach(() => cleanup());

it('タイトル文字列が表示される', async () => {
render(<App />);
expect(screen.getByText('Sample Chat App')).toBeTruthy();
});
});
58 changes: 58 additions & 0 deletions test/components/Message.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { render, cleanup, screen, waitFor } from '@testing-library/react';
import { userFactory } from '@/../test/factories/user';
import { messageFactory } from '@/../test/factories/message';
import { Timestamp } from 'firebase/firestore';

const sender = userFactory.build({
id: 'user-id',
name: 'テストユーザー',
photoUrl: 'user-photo-url',
});
vi.mock('@/context/UsersContext', () => {
return {
useUsers: { usersById: { 'user-id': [sender] } },
};
});

describe('Message', async () => {
const { Message } = await import('@/components/Message');

afterEach(() => cleanup());

vi.mock('@/context/UsersContext', () => {
return {
useUsers: { usersById: { 'user-id': [sender] } },
};
});

const message = messageFactory.build({
content: `テストのメッセージ`,
senderId: 'user-id',
createdAt: Timestamp.fromDate(new Date('2022-07-01 00:00:00+09:00')),
});

it('loading中はloadingメッセージが表示される', () => {
render(<Message message={message} />);
expect(screen.getByText('loading...')).toBeTruthy();
});

it('アイコン画像が表示される', () => {
render(<Message message={message} />);
waitFor(() => expect(screen.getByRole('img').getAttribute('src')).toBe('user-photo-url'));
});

it('送信者の名前が表示される', () => {
render(<Message message={message} />);
waitFor(() => expect(screen.getByText('テストユーザー')).toBeTruthy());
});

it('送信時間が表示される', () => {
render(<Message message={message} />);
waitFor(() => expect(screen.getByText('2022-07-01 00:00')).toBeTruthy());
});

it('メッセージが表示される', () => {
render(<Message message={message} />);
waitFor(() => expect(screen.getByText('テストのメッセージ')).toBeTruthy());
});
});
31 changes: 31 additions & 0 deletions test/contexts/UsersContext.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { renderHook } from '@testing-library/react-hooks';
import { useUsers, UsersProvider } from '@/contexts/UsersContext';
import { ReactNode } from 'react';

describe('useUsers', () => {
const wrapper = ({ children }: { children: ReactNode }) => <UsersProvider>{children}</UsersProvider>;

vi.mock('@/hooks/useCollectionData', () => {
return {
useCollectionData: () => [[{ id: 'test-user-uid', name: 'てすたろう' }], false],
};
});

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

it('usersとusersById,loadingを返す', async () => {
const { result } = renderHook(() => useUsers(), { wrapper });
expect(result.current).toEqual({
users: [{ id: 'test-user-uid', name: 'てすたろう' }],
usersById: {
'test-user-uid': {
id: 'test-user-uid',
name: 'てすたろう',
},
},
loading: false,
});
});
});
9 changes: 8 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@
dependencies:
"@babel/helper-plugin-utils" "^7.22.5"

"@babel/runtime@^7.12.5":
"@babel/runtime@^7.12.5", "@babel/runtime@^7.21.0":
version "7.22.6"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.22.6.tgz#57d64b9ae3cff1d67eb067ae117dac087f5bd438"
integrity sha512-wDb5pWm4WDdF6LFUde3Jl8WzPA+3ZbxYqkC6xAXuD3irdEHN1k0NfTRrJD8ZD378SJ61miMLCqIOXYhd8x+AJQ==
Expand Down Expand Up @@ -1502,6 +1502,13 @@ data-urls@^4.0.0:
whatwg-mimetype "^3.0.0"
whatwg-url "^12.0.0"

date-fns@^2.30.0:
version "2.30.0"
resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-2.30.0.tgz#f367e644839ff57894ec6ac480de40cae4b0f4d0"
integrity sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==
dependencies:
"@babel/runtime" "^7.21.0"

debug@4, debug@^4.1.0, debug@^4.1.1, debug@^4.3.2, debug@^4.3.4:
version "4.3.4"
resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865"
Expand Down