Add frontend component tests (#144)

* Install react-testing-library

* Add some trivial tests with snapshot

* Add File transfer tests

* Add Home component test

* Add Chat tests

* Add tests for nav

* 100% coverage for About component

* 100% coverage room link

* 100% coverage for RoomLocked

* 100% coverage for T component

* 100% coverage Settings

* More 90% coverage for Chat component

* Ignore some file from coverage

* 100% coverage fo redux actions

* 100% coverage for translations

* Near 100% coverage for reducer

* Better coverage for Home component

* Run tests in circleCI
This commit is contained in:
Jérémie Pardou-Piquemal 2020-06-10 21:46:56 +02:00 committed by GitHub
parent 533ffe8cae
commit 50cefcb459
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
66 changed files with 5777 additions and 462 deletions

View File

@ -1,18 +1,10 @@
# Javascript Node CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-javascript/ for more details
#
version: 2
jobs:
build:
docker:
# specify the version you desire here
- image: circleci/node:8.10
# Specify service dependencies here if necessary
# CircleCI maintains a library of pre-built images
# documented at https://circleci.com/docs/2.0/circleci-images/
# - image: circleci/mongo:3.4.4
jobs:
test-job:
docker:
- image: 'circleci/node:lts'
working_directory: ~/repo
@ -22,15 +14,34 @@ jobs:
# Download and cache dependencies
- restore_cache:
keys:
- v1-dependencies-{{ checksum "yarn.lock" }}
- dependencies-{{ checksum "yarn.lock" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- dependencies-
- run: yarn install
- run: yarn setup
- save_cache:
paths:
- node_modules
key: v1-dependencies-{{ checksum "yarn.lock" }}
- client/node_modules
- server/node_modules
key: dependencies-{{ checksum "yarn.lock" }}
- run: yarn test
- run:
command: yarn test
environment:
TZ: UTC
REACT_APP_COMMIT_SHA: some_sha
- store_artifacts: # For coverage report
path: client/coverage
orbs: # declare what orbs we are going to use
node: circleci/node@2.0.2 # the node orb provides common node-related configuration
version: 2.1
workflows:
tests:
jobs:
- test-job

View File

@ -2,3 +2,4 @@ REACT_APP_API_HOST=localhost
REACT_APP_API_PROTOCOL=http
REACT_APP_API_PORT=3001
REACT_APP_COMMIT_SHA=some_sha
TZ=UTC

View File

@ -43,7 +43,8 @@
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"test": "react-scripts test --env=jest-environment-jsdom-sixteen",
"coverage": "react-scripts test --env=jest-environment-jsdom-sixteen --coverage --watchAll=false",
"eject": "react-scripts eject"
},
"eslintConfig": {
@ -62,8 +63,13 @@
]
},
"devDependencies": {
"@peculiar/webcrypto": "^1.1.1",
"@testing-library/jest-dom": "^5.5.0",
"@testing-library/react": "^10.0.4",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.12.1",
"enzyme-to-json": "^3.3.5"
"enzyme-to-json": "^3.3.5",
"jest-environment-jsdom-sixteen": "^1.0.3",
"jest-fetch-mock": "^3.0.3"
}
}

View File

@ -0,0 +1,53 @@
import * as actions from './app';
describe('App actions', () => {
it('should create an action to scroll to bottom', () => {
expect(actions.setScrolledToBottom('test')).toEqual({
type: 'SET_SCROLLED_TO_BOTTOM',
payload: 'test',
});
});
it('should create an action to close modal', () => {
expect(actions.closeModal()).toEqual({
type: 'CLOSE_MODAL',
});
});
it('should create an action to open modal', () => {
expect(actions.openModal('test')).toEqual({
type: 'OPEN_MODAL',
payload: 'test',
});
});
it('should create an action to clear activities', () => {
const mockDispatch = jest.fn();
actions.clearActivities()(mockDispatch);
expect(mockDispatch).toHaveBeenLastCalledWith({
type: 'CLEAR_ACTIVITIES',
});
});
it('should create all actions', () => {
const mockDispatch = jest.fn();
const actionsResults = [
[actions.toggleWindowFocus('test'), 'TOGGLE_WINDOW_FOCUS'],
[actions.showNotice('test'), 'SHOW_NOTICE'],
[actions.toggleSoundEnabled('test'), 'TOGGLE_SOUND_ENABLED'],
[actions.toggleSocketConnected('test'), 'TOGGLE_SOCKET_CONNECTED'],
[actions.createUser('test'), 'CREATE_USER'],
[actions.setLanguage('test'), 'CHANGE_LANGUAGE'],
];
actionsResults.forEach(([action, type]) => {
action(mockDispatch);
expect(mockDispatch).toHaveBeenLastCalledWith({
type,
payload: 'test',
});
});
});
});

View File

@ -0,0 +1,49 @@
import * as actions from './encrypted_messages';
import { getSocket } from 'utils/socket';
import { prepare as prepareMessage, process as processMessage } from 'utils/message';
jest.mock('utils/message', () => {
return {
prepare: jest
.fn()
.mockResolvedValue({ original: { type: 'messageType', payload: 'test' }, toSend: 'encryptedpayload' }),
process: jest.fn().mockResolvedValue({ type: 'messageType', payload: 'test' }),
};
});
const mockEmit = jest.fn();
jest.mock('utils/socket', () => {
return {
getSocket: jest.fn().mockImplementation(() => ({
emit: mockEmit,
})),
};
});
describe('Encrypted messages actions', () => {
it('should create an action to send message', async () => {
const mockDispatch = jest.fn();
await actions.sendEncryptedMessage({ payload: 'payload' })(mockDispatch, jest.fn().mockReturnValue({ state: {} }));
expect(prepareMessage).toHaveBeenLastCalledWith({ payload: 'payload' }, { state: {} });
expect(mockDispatch).toHaveBeenLastCalledWith({ payload: 'test', type: 'SEND_ENCRYPTED_MESSAGE_messageType' });
expect(getSocket().emit).toHaveBeenLastCalledWith('ENCRYPTED_MESSAGE', 'encryptedpayload');
});
it('should create an action to receive message', async () => {
const mockDispatch = jest.fn();
await actions.receiveEncryptedMessage({ payload: 'encrypted' })(
mockDispatch,
jest.fn().mockReturnValue({ state: {} }),
);
expect(processMessage).toHaveBeenLastCalledWith({ payload: 'encrypted' }, { state: {} });
expect(mockDispatch).toHaveBeenLastCalledWith({
payload: { payload: 'test', state: { state: {} } },
type: 'RECEIVE_ENCRYPTED_MESSAGE_messageType',
});
});
});

View File

@ -1,3 +1,5 @@
/* istanbul ignore file */
export * from './app'
export * from './unencrypted_messages'
export * from './encrypted_messages'

View File

@ -0,0 +1,125 @@
import * as actions from './unencrypted_messages';
import { getSocket } from 'utils/socket';
const mockEmit = jest.fn((_type, _null, callback) => {
callback({ isLocked: true });
});
jest.mock('utils/socket', () => {
return {
getSocket: jest.fn().mockImplementation(() => ({
emit: mockEmit,
})),
};
});
describe('Reveice unencrypted message actions', () => {
it('should create no action', () => {
const mockDispatch = jest.fn();
actions.receiveUnencryptedMessage('FAKE')(mockDispatch, jest.fn().mockReturnValue({}));
expect(mockDispatch).not.toHaveBeenCalled();
});
it('should create user enter action', () => {
const mockDispatch = jest.fn();
actions.receiveUnencryptedMessage('USER_ENTER', 'test')(mockDispatch, jest.fn().mockReturnValue({ state: {} }));
expect(mockDispatch).toHaveBeenLastCalledWith({ type: 'USER_ENTER', payload: 'test' });
});
it('should create user exit action', () => {
const mockDispatch = jest.fn();
const state = {
room: {
members: [
{ publicKey: { n: 'alankey' }, id: 'alankey', username: 'alan' },
{ publicKey: { n: 'dankey' }, id: 'dankey', username: 'dan' },
{ publicKey: { n: 'alicekey' }, id: 'alicekey', username: 'dan' },
],
},
};
const mockGetState = jest.fn().mockReturnValue(state);
const payload1 = [
{ publicKey: { n: 'alankey' } },
{ publicKey: { n: 'dankey' } },
{ publicKey: { n: 'alicekey' } },
];
const payload2 = [{ publicKey: { n: 'dankey' } }, { publicKey: { n: 'alicekey' } }];
// Nobody left
actions.receiveUnencryptedMessage('USER_EXIT', payload1)(mockDispatch, mockGetState);
expect(mockDispatch).not.toHaveBeenCalled();
actions.receiveUnencryptedMessage('USER_EXIT', payload2)(mockDispatch, mockGetState);
expect(mockDispatch).toHaveBeenLastCalledWith({
payload: {
id: 'alankey',
members: [{ publicKey: { n: 'dankey' } }, { publicKey: { n: 'alicekey' } }],
username: 'alan',
},
type: 'USER_EXIT',
});
});
it('should create receive toggle lock room action', () => {
const mockDispatch = jest.fn();
const state = {
room: {
members: [
{ publicKey: { n: 'alankey' }, id: 'idalan', username: 'alan' },
{ publicKey: { n: 'dankey' }, id: 'iddan', username: 'dan' },
],
},
};
const mockGetState = jest.fn().mockReturnValue(state);
const payload = { publicKey: { n: 'alankey' } };
actions.receiveUnencryptedMessage('TOGGLE_LOCK_ROOM', payload)(mockDispatch, mockGetState);
expect(mockDispatch).toHaveBeenLastCalledWith({
payload: { id: 'idalan', locked: undefined, username: 'alan' },
type: 'RECEIVE_TOGGLE_LOCK_ROOM',
});
});
it('should create receive toggle lock room action', () => {
const mockDispatch = jest.fn();
const state = {
user: {
username: 'alan',
id: 'idalan',
},
};
const mockGetState = jest.fn().mockReturnValue(state);
actions.sendUnencryptedMessage('TOGGLE_LOCK_ROOM')(mockDispatch, mockGetState);
expect(mockDispatch).toHaveBeenLastCalledWith({
payload: { locked: true, sender: 'idalan', username: 'alan' },
type: 'TOGGLE_LOCK_ROOM',
});
});
});
describe('Send unencrypted message actions', () => {
it('should create no action', () => {
const mockDispatch = jest.fn();
actions.sendUnencryptedMessage('FAKE')(mockDispatch, jest.fn().mockReturnValue({}));
expect(mockDispatch).not.toHaveBeenCalled();
});
it('should create toggle lock room action', () => {
const mockDispatch = jest.fn();
const state = {
user: {
username: 'alan',
id: 'idalan',
},
};
const mockGetState = jest.fn().mockReturnValue(state);
actions.sendUnencryptedMessage('TOGGLE_LOCK_ROOM')(mockDispatch, mockGetState);
expect(mockDispatch).toHaveBeenLastCalledWith({
payload: { locked: true, sender: 'idalan', username: 'alan' },
type: 'TOGGLE_LOCK_ROOM',
});
});
});

View File

@ -1,3 +1,4 @@
/* istanbul ignore file */
let host
let protocol
let port

View File

@ -1,3 +1,4 @@
/* istanbul ignore file */
import config from './config'
export default (resourceName = '') => {

View File

@ -0,0 +1,52 @@
import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react';
import About from '.';
import fetchMock from 'jest-fetch-mock';
jest.useFakeTimers();
// Mock Api generator
jest.mock('../../api/generator', () => {
return path => {
return `http://fakedomain/${path}`;
};
});
describe('About component', () => {
afterEach(() => {
fetchMock.resetMocks();
});
it('should display', async () => {
const { asFragment } = render(<About roomId={'test'} />);
expect(asFragment()).toMatchSnapshot();
});
it('should report abuse', async () => {
const { getByText, queryByText } = render(<About roomId={'test'} />);
expect(queryByText('Thank you!')).not.toBeInTheDocument();
fireEvent.click(getByText('Submit'));
expect(fetchMock).toHaveBeenCalledWith('http://fakedomain/abuse/test', { method: 'POST' });
expect(getByText('Thank you!')).toBeInTheDocument();
});
it('should change room id', async () => {
const { getByPlaceholderText, getByText, queryByText } = render(<About roomId={'test'} />);
expect(queryByText('Thank you!')).not.toBeInTheDocument();
fireEvent.change(getByPlaceholderText('Room ID'), { target: { value: 'newRoomName' } });
jest.runAllTimers();
fireEvent.click(getByText('Submit'));
expect(fetchMock).toHaveBeenLastCalledWith('http://fakedomain/abuse/newRoomName', { method: 'POST' });
});
});

View File

@ -0,0 +1,513 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`About component should display 1`] = `
<DocumentFragment>
<div
class="base"
>
<div
class="links"
>
<div>
<a
href="#version"
>
Version
</a>
</div>
<div>
<a
href="#software"
>
Software
</a>
</div>
<div>
<a
href="#report-abuse"
>
Report Abuse
</a>
</div>
<div>
<a
href="#acceptable-use"
>
Acceptable Use Policy
</a>
</div>
<div>
<a
href="#disclaimer"
>
Disclaimer
</a>
</div>
<div>
<a
href="#terms"
>
Terms of Service
</a>
</div>
<div>
<a
href="#contact"
>
Contact
</a>
</div>
<div>
<a
href="#donate"
>
Donate
</a>
</div>
</div>
<section
id="version"
>
<h4>
Version
</h4>
<p>
Commit SHA:
<a
href="https://github.com/darkwire/darkwire.io/commit/some_sha"
target="_blank"
>
some_sha
</a>
</p>
</section>
<section
id="software"
>
<h4>
Software
</h4>
<p>
This software uses the
<a
href="https://developer.mozilla.org/en-US/docs/Web/API/Crypto"
rel="noopener noreferrer"
target="_blank"
>
Web Cryptography API
</a>
to encrypt data which is transferred using
<a
href="https://en.wikipedia.org/wiki/WebSocket"
rel="noopener noreferrer"
target="_blank"
>
secure WebSockets
</a>
. Messages are never stored on a server or sent over the wire in plain-text.
</p>
<p>
We believe in privacy and transparency.  
<a
href="https://github.com/darkwire/darkwire.io"
rel="noopener noreferrer"
target="_blank"
>
View the source code and documentation on GitHub.
</a>
</p>
</section>
<section
id="report-abuse"
>
<h4>
Report Abuse
</h4>
<p>
We encourage you to report problematic content to us. Please keep in mind that to help ensure the safety, confidentiality and security of your messages, we do not have the contents of messages available to us, which limits our ability to verify the report and take action.
</p>
<p>
When needed, you can take a screenshot of the content and share it, along with any available contact info, with appropriate law enforcement authorities.
</p>
<p>
To report any content, email us at abuse[at]darkwire.io or submit the room ID below to report anonymously.
</p>
<form>
<div>
<div
class="input-group"
>
<input
class="form-control"
placeholder="Room ID"
type="text"
value="test"
/>
<div
class="input-group-append"
>
<button
class="btn btn-secondary"
type="submit"
>
Submit
</button>
</div>
</div>
</div>
</form>
<br />
<p>
If you feel you or anyone else is in immediate danger, please contact your local emergency services.
</p>
<p>
If you receive content from someone who wishes to hurt themselves, and you're concerned for their safety, please contact your local emergency services or a
<a
href="https://faq.whatsapp.com/en/general/28030010"
>
suicide prevention hotline
</a>
.
</p>
<p>
If you receive or encounter content indicating abuse or exploitation of a child, please contact the
<a
href="http://www.missingkids.com"
>
National Center for Missing and Exploited Children (NCMEC)
</a>
.
</p>
</section>
<section
id="acceptable-use"
>
<h4>
Acceptable Use Policy
</h4>
<p>
This Acceptable Use Policy (this “Policy”) describes prohibited uses of the web services offered by Darkwire and its affiliates (the “Services”) and the website located at https://darkwire.io (the “Darkwire Site”). The examples described in this Policy are not exhaustive. We may modify this Policy at any time by posting a revised version on the Darkwire Site. By using the Services or accessing the Darkwire Site, you agree to the latest version of this Policy. If you violate the Policy or authorize or help others to do so, we may suspend or terminate your use of the Services.
</p>
<strong>
No Illegal, Harmful, or Offensive Use or Content
</strong>
<p>
You may not use, or encourage, promote, facilitate or instruct others to use, the Services or Darkwire Site for any illegal, harmful, fraudulent, infringing or offensive use, or to transmit, store, display, distribute or otherwise make available content that is illegal, harmful, fraudulent, infringing or offensive. Prohibited activities or content include:
</p>
<ul>
<li>
<strong>
Illegal, Harmful or Fraudulent Activities.
</strong>
Any activities that are illegal, that violate the rights of others, or that may be harmful to others, our operations or reputation, including disseminating, promoting or facilitating child pornography, offering or disseminating fraudulent goods, services, schemes, or promotions, make-money-fast schemes, ponzi and pyramid schemes, phishing, or pharming.
</li>
<li>
<strong>
Infringing Content.
</strong>
Content that infringes or misappropriates the intellectual property or proprietary rights of others.
</li>
<li>
<strong>
Offensive Content.
</strong>
Content that is defamatory, obscene, abusive, invasive of privacy, or otherwise objectionable, including content that constitutes child pornography, relates to bestiality, or depicts non-consensual sex acts.
</li>
<li>
<strong>
Harmful Content.
</strong>
Content or other computer technology that may damage, interfere with, surreptitiously intercept, or expropriate any system, program, or data, including viruses, Trojan horses, worms, time bombs, or cancelbots.
</li>
</ul>
<strong>
No Security Violations
</strong>
<br />
You may not use the Services to violate the security or integrity of any network, computer or communications system, software application, or network or computing device (each, a “System”). Prohibited activities include:
<ul>
<li>
<strong>
Unauthorized Access.
</strong>
Accessing or using any System without permission, including attempting to probe, scan, or test the vulnerability of a System or to breach any security or authentication measures used by a System.
</li>
<li>
<strong>
Interception.
</strong>
Monitoring of data or traffic on a System without permission.
</li>
<li>
<strong>
Falsification of Origin.
</strong>
Forging TCP-IP packet headers, e-mail headers, or any part of a message describing its origin or route. The legitimate use of aliases and anonymous remailers is not prohibited by this provision.
</li>
</ul>
<strong>
No Network Abuse
</strong>
<br />
You may not make network connections to any users, hosts, or networks unless you have permission to communicate with them. Prohibited activities include:
<ul>
<li>
<strong>
Monitoring or Crawling.
</strong>
Monitoring or crawling of a System that impairs or disrupts the System being monitored or crawled.
</li>
<li>
<strong>
Denial of Service (DoS).
</strong>
Inundating a target with communications requests so the target either cannot respond to legitimate traffic or responds so slowly that it becomes ineffective.
</li>
<li>
<strong>
Intentional Interference.
</strong>
Interfering with the proper functioning of any System, including any deliberate attempt to overload a system by mail bombing, news bombing, broadcast attacks, or flooding techniques.
</li>
<li>
<strong>
Operation of Certain Network Services.
</strong>
Operating network services like open proxies, open mail relays, or open recursive domain name servers.
</li>
<li>
<strong>
Avoiding System Restrictions.
</strong>
Using manual or electronic means to avoid any use limitations placed on a System, such as access and storage restrictions.
</li>
</ul>
<strong>
No E-Mail or Other Message Abuse
</strong>
<br />
You will not distribute, publish, send, or facilitate the sending of unsolicited mass e-mail or other messages, promotions, advertising, or solicitations (like “spam”), including commercial advertising and informational announcements. You will not alter or obscure mail headers or assume a senders identity without the senders explicit permission. You will not collect replies to messages sent from another internet service provider if those messages violate this Policy or the acceptable use policy of that provider.
<strong>
Our Monitoring and Enforcement
</strong>
<br />
We reserve the right, but do not assume the obligation, to investigate any violation of this Policy or misuse of the Services or Darkwire Site. We may:
<ul>
<li>
investigate violations of this Policy or misuse of the Services or Darkwire Site; or
</li>
<li>
remove, disable access to, or modify any content or resource that violates this Policy or any other agreement we have with you for use of the Services or the Darkwire Site.
</li>
<li>
We may report any activity that we suspect violates any law or regulation to appropriate law enforcement officials, regulators, or other appropriate third parties. Our reporting may include disclosing appropriate customer information. We also may cooperate with appropriate law enforcement agencies, regulators, or other appropriate third parties to help with the investigation and prosecution of illegal conduct by providing network and systems information related to alleged violations of this Policy.
</li>
</ul>
Reporting of Violations of this Policy
<br />
If you become aware of any violation of this Policy, you will immediately notify us and provide us with assistance, as requested, to stop or remedy the violation. To report any violation of this Policy, please follow our abuse reporting process.
</section>
<section
id="terms"
>
<h4>
Terms of Service ("Terms")
</h4>
<p>
Last updated: December 11, 2017
</p>
<p>
Please read these Terms of Service ("Terms", "Terms of Service") carefully before using the https://darkwire.io website (the "Service") operated by Darkwire ("us", "we", or "our").
</p>
<p>
Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all visitors, users and others who access or use the Service.
</p>
<p>
By accessing or using the Service you agree to be bound by these Terms. If you disagree with any part of the terms then you may not access the Service.
</p>
<strong>
Links To Other Web Sites
</strong>
<p>
Our Service may contain links to third-party web sites or services that are not owned or controlled by Darkwire.
</p>
<p>
Darkwire has no control over, and assumes no responsibility for, the content, privacy policies, or practices of any third party web sites or services. You further acknowledge and agree that Darkwire shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods or services available on or through any such web sites or services.
</p>
<p>
We strongly advise you to read the terms and conditions and privacy policies of any third-party web sites or services that you visit.
</p>
<strong>
Termination
</strong>
<p>
We may terminate or suspend access to our Service immediately, without prior notice or liability, for any reason whatsoever, including without limitation if you breach the Terms.
</p>
<p>
All provisions of the Terms which by their nature should survive termination shall survive termination, including, without limitation, ownership provisions, warranty disclaimers, indemnity and limitations of liability.
</p>
<strong>
Governing Law
</strong>
<p>
These Terms shall be governed and construed in accordance with the laws of New York, United States, without regard to its conflict of law provisions.
</p>
<p>
Our failure to enforce any right or provision of these Terms will not be considered a waiver of those rights. If any provision of these Terms is held to be invalid or unenforceable by a court, the remaining provisions of these Terms will remain in effect. These Terms constitute the entire agreement between us regarding our Service, and supersede and replace any prior agreements we might have between us regarding the Service.
</p>
</section>
<section
id="disclaimer"
>
<h4>
Disclaimer
</h4>
<p
class="bold"
>
WARNING: Darkwire does not mask IP addresses nor can verify the integrity of parties recieving messages.  Proceed with caution and always confirm recipients beforre starting a chat session.
</p>
<p>
Please also note that
<strong>
ALL CHATROOMS
</strong>
are public.  Anyone can guess your room URL. If you need a more-private room, use the lock feature or set the URL manually by entering a room ID after "darkwire.io/".
</p>
<br />
<strong>
No Warranties; Exclusion of Liability; Indemnification
</strong>
<p>
<strong>
OUR WEBSITE IS OPERATED BY Darkwire ON AN "AS IS," "AS AVAILABLE" BASIS, WITHOUT REPRESENTATIONS OR WARRANTIES OF ANY KIND. TO THE FULLEST EXTENT PERMITTED BY LAW, Darkwire SPECIFICALLY DISCLAIMS ALL WARRANTIES AND CONDITIONS OF ANY KIND, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NONINFRINGEMENT FOR OUR WEBSITE AND ANY CONTRACTS AND SERVICES YOU PURCHASE THROUGH IT. Darkwire SHALL NOT HAVE ANY LIABILITY OR RESPONSIBILITY FOR ANY ERRORS OR OMISSIONS IN THE CONTENT OF OUR WEBSITE, FOR CONTRACTS OR SERVICES SOLD THROUGH OUR WEBSITE, FOR YOUR ACTION OR INACTION IN CONNECTION WITH OUR WEBSITE OR FOR ANY DAMAGE TO YOUR COMPUTER OR DATA OR ANY OTHER DAMAGE YOU MAY INCUR IN CONNECTION WITH OUR WEBSITE. YOUR USE OF OUR WEBSITE AND ANY CONTRACTS OR SERVICES ARE AT YOUR OWN RISK. IN NO EVENT SHALL EITHER Darkwire OR THEIR AGENTS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR IN ANY WAY CONNECTED WITH THE USE OF OUR WEBSITE, CONTRACTS AND SERVICES PURCHASED THROUGH OUR WEBSITE, THE DELAY OR INABILITY TO USE OUR WEBSITE OR OTHERWISE ARISING IN CONNECTION WITH OUR WEBSITE, CONTRACTS OR RELATED SERVICES, WHETHER BASED ON CONTRACT, TORT, STRICT LIABILITY OR OTHERWISE, EVEN IF ADVISED OF THE POSSIBILITY OF ANY SUCH DAMAGES. IN NO EVENT SHALL Darkwires LIABILITY FOR ANY DAMAGE CLAIM EXCEED THE AMOUNT PAID BY YOU TO Darkwire FOR THE TRANSACTION GIVING RISE TO SUCH DAMAGE CLAIM.
</strong>
</p>
<p>
<strong>
SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE ABOVE EXCLUSION MAY NOT APPLY TO YOU.
</strong>
</p>
<p>
<strong>
WITHOUT LIMITING THE FOREGOING, Darkwire DO NOT REPRESENT OR WARRANT THAT THE INFORMATION ON THE WEBITE IS ACCURATE, COMPLETE, RELIABLE, USEFUL, TIMELY OR CURRENT OR THAT OUR WEBSITE WILL OPERATE WITHOUT INTERRUPTION OR ERROR.
</strong>
</p>
<p>
<strong>
YOU AGREE THAT ALL TIMES, YOU WILL LOOK TO ATTORNEYS FROM WHOM YOU PURCHASE SERVICES FOR ANY CLAIMS OF ANY NATURE, INCLUDING LOSS, DAMAGE, OR WARRANTY. Darkwire AND THEIR RESPECTIVE AFFILIATES MAKE NO REPRESENTATION OR GUARANTEES ABOUT ANY CONTRACTS AND SERVICES OFFERED THROUGH OUR WEBSITE.
</strong>
</p>
<p>
<strong>
Darkwire MAKES NO REPRESENTATION THAT CONTENT PROVIDED ON OUR WEBSITE, CONTRACTS, OR RELATED SERVICES ARE APPLICABLE OR APPROPRIATE FOR USE IN ALL JURISDICTIONS.
</strong>
</p>
<strong>
Indemnification
</strong>
<p>
You agree to defend, indemnify and hold Darkwire harmless from and against any and all claims, damages, costs and expenses, including attorneys' fees, arising from or related to your use of our Website or any Contracts or Services you purchase through it.
</p>
<strong>
Changes
</strong>
<p>
We reserve the right, at our sole discretion, to modify or replace these Terms at any time. If a revision is material we will try to provide at least 30 days notice prior to any new terms taking effect. What constitutes a material change will be determined at our sole discretion.
</p>
<p>
By continuing to access or use our Service after those revisions become effective, you agree to be bound by the revised terms. If you do not agree to the new terms, please stop using the Service.
</p>
<strong>
Contact Us
</strong>
<p>
If you have any questions about these Terms, please contact us at hello[at]darkwire.io.
</p>
</section>
<section
id="contact"
>
<h4>
Contact
</h4>
<p>
Questions/comments? Email us at hello[at]darkwire.io
</p>
<p>
Found a bug or want a new feature?
<a
href="https://github.com/darkwire/darkwire.io/issues"
rel="noopener noreferrer"
target="_blank"
>
Open a ticket on Github
</a>
.
</p>
</section>
<section
id="donate"
>
<h4>
Donate
</h4>
<p>
Darkwire is maintained and hosted by two developers with full-time jobs. If you get some value from this service we would appreciate any donation you can afford. We use these funds for server and DNS costs. Thank you!
</p>
<strong>
Bitcoin
</strong>
<p>
189sPnHGcjP5uteg2UuNgcJ5eoaRAP4Bw4
</p>
<strong>
Ethereum
</strong>
<p>
0x36dc407bB28aA1EE6AafBee0379Fe6Cff881758E
</p>
<strong>
Litecoin
</strong>
<p>
LUViQeSggBBtYoN2qNtXSuxYoRMzRY8CSX
</p>
<strong>
PayPal:
</strong>
<br />
<form
action="https://www.paypal.com/cgi-bin/webscr"
method="post"
target="_blank"
>
<input
name="cmd"
type="hidden"
value="_s-xclick"
/>
<input
name="hosted_button_id"
type="hidden"
value="UAH5BCLA9Y8VW"
/>
<input
alt="PayPal - The safer, easier way to pay online!"
border="0"
name="submit"
src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif"
type="image"
/>
<img
alt=""
border="0"
height="1"
src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif"
width="1"
/>
</form>
</section>
</div>
</DocumentFragment>
`;

View File

@ -0,0 +1,297 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import sanitizeHtml from 'sanitize-html';
import FileTransfer from 'components/FileTransfer';
import { CornerDownRight } from 'react-feather';
import { getSelectedText, hasTouchSupport } from '../../utils/dom';
// Disable for now
// import autosize from 'autosize'
export class Chat extends Component {
constructor(props) {
super(props);
this.state = {
message: '',
touchSupport: hasTouchSupport,
shiftKeyDown: false,
};
this.commands = [
{
command: 'nick',
description: 'Changes nickname.',
paramaters: ['{username}'],
usage: '/nick {username}',
scope: 'global',
action: params => {
// eslint-disable-line
let newUsername = params.join(' ') || ''; // eslint-disable-line
// Remove things that arent digits or chars
newUsername = newUsername.replace(/[^A-Za-z0-9]/g, '-');
const errors = [];
if (!newUsername.trim().length) {
errors.push('Username cannot be blank');
}
if (newUsername.toString().length > 16) {
errors.push('Username cannot be greater than 16 characters');
}
if (!newUsername.match(/^[A-Z]/i)) {
errors.push('Username must start with a letter');
}
if (errors.length) {
return this.props.showNotice({
message: `${errors.join(', ')}`,
level: 'error',
});
}
this.props.sendEncryptedMessage({
type: 'CHANGE_USERNAME',
payload: {
id: this.props.userId,
newUsername,
currentUsername: this.props.username,
},
});
},
},
{
command: 'help',
description: 'Shows a list of commands.',
paramaters: [],
usage: '/help',
scope: 'local',
action: params => {
// eslint-disable-line
const validCommands = this.commands.map(command => `/${command.command}`);
this.props.showNotice({
message: `Valid commands: ${validCommands.sort().join(', ')}`,
level: 'info',
});
},
},
{
command: 'me',
description: 'Invoke virtual action',
paramaters: ['{action}'],
usage: '/me {action}',
scope: 'global',
action: params => {
// eslint-disable-line
const actionMessage = params.join(' ');
if (!actionMessage.trim().length) {
return false;
}
this.props.sendEncryptedMessage({
type: 'USER_ACTION',
payload: {
action: actionMessage,
},
});
},
},
{
command: 'clear',
description: 'Clears the chat screen',
paramaters: [],
usage: '/clear',
scope: 'local',
action: (params = null) => {
// eslint-disable-line
this.props.clearActivities();
},
},
];
}
componentDidMount() {
if (!hasTouchSupport) {
// Disable for now due to vary issues:
// Paste not working, shift+enter line breaks
// autosize(this.textInput);
this.textInput.addEventListener('autosize:resized', () => {
this.props.scrollToBottom();
});
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.focusChat) {
if (!getSelectedText()) {
// Don't focus for now, evaluate UX benfits
// this.textInput.focus()
}
}
}
componentDidUpdate(nextProps, nextState) {
if (!nextState.message.trim().length) {
// autosize.update(this.textInput)
}
}
handleKeyUp(e) {
if (e.key === 'Shift') {
this.setState({
shiftKeyDown: false,
});
}
}
handleKeyPress(e) {
if (e.key === 'Shift') {
this.setState({
shiftKeyDown: true,
});
}
// Fix when autosize is enabled - line breaks require shift+enter twice
if (e.key === 'Enter' && !hasTouchSupport && !this.state.shiftKeyDown) {
e.preventDefault();
if (this.canSend()) {
this.sendMessage();
} else {
this.setState({
message: '',
});
}
}
}
executeCommand(command) {
const commandToExecute = this.commands.find(cmnd => cmnd.command === command.command);
if (commandToExecute) {
const { params } = command;
const commandResult = commandToExecute.action(params);
return commandResult;
}
return null;
}
handleSendClick() {
this.sendMessage.bind(this);
this.textInput.focus();
}
handleFormSubmit(evt) {
evt.preventDefault();
this.sendMessage();
}
parseCommand(message) {
const commandTrigger = {
command: null,
params: [],
};
if (message.charAt(0) === '/') {
const parsedCommand = message.replace('/', '').split(' ');
commandTrigger.command = sanitizeHtml(parsedCommand[0]) || null;
// Get params
if (parsedCommand.length >= 2) {
for (let i = 1; i < parsedCommand.length; i++) {
commandTrigger.params.push(parsedCommand[i]);
}
}
return commandTrigger;
}
return false;
}
sendMessage() {
if (!this.canSend()) {
return;
}
const { message } = this.state;
const isCommand = this.parseCommand(message);
if (isCommand) {
const res = this.executeCommand(isCommand);
if (res === false) {
return;
}
} else {
this.props.sendEncryptedMessage({
type: 'TEXT_MESSAGE',
payload: {
text: message,
timestamp: Date.now(),
},
});
}
this.setState({
message: '',
});
}
handleInputChange(evt) {
this.setState({
message: evt.target.value,
});
}
canSend() {
return this.state.message.trim().length;
}
render() {
const touchSupport = this.state.touchSupport;
return (
<form onSubmit={this.handleFormSubmit.bind(this)} className="chat-preflight-container">
<textarea
rows="1"
onKeyUp={this.handleKeyUp.bind(this)}
onKeyDown={this.handleKeyPress.bind(this)}
ref={input => {
this.textInput = input;
}}
autoFocus
className="chat"
value={this.state.message}
placeholder={this.props.translations.typePlaceholder}
onChange={this.handleInputChange.bind(this)}
/>
<div className="input-controls">
<FileTransfer sendEncryptedMessage={this.props.sendEncryptedMessage} />
{touchSupport && (
<button
onClick={this.handleSendClick.bind(this)}
className={`icon is-right send btn btn-link ${this.canSend() ? 'active' : ''}`}
title="Send"
>
<CornerDownRight className={this.canSend() ? '' : 'disabled'} />
</button>
)}
</div>
</form>
);
}
}
Chat.propTypes = {
sendEncryptedMessage: PropTypes.func.isRequired,
showNotice: PropTypes.func.isRequired,
userId: PropTypes.string.isRequired,
username: PropTypes.string.isRequired,
clearActivities: PropTypes.func.isRequired,
focusChat: PropTypes.bool.isRequired,
scrollToBottom: PropTypes.func.isRequired,
translations: PropTypes.object.isRequired,
};
export default Chat;

View File

@ -1,17 +1,253 @@
import React from 'react'
import { mount } from 'enzyme'
import toJson from 'enzyme-to-json'
import { Chat } from './index.js'
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
const sendEncryptedMessage = jest.fn()
import { Chat } from './Chat';
test('Chat Component', () => {
const component = mount(
<Chat scrollToBottom={() => {}} focusChat={false} userId="foo" username="user" showNotice={() => {}} clearActivities={() => {}} sendEncryptedMessage={sendEncryptedMessage} translations={{}}/>
)
import * as dom from 'utils/dom';
const componentJSON = toJson(component)
const translations = {
typePlaceholder: 'inputplaceholder',
};
expect(component).toMatchSnapshot()
expect(componentJSON.children.length).toBe(1)
})
// Fake date
jest.spyOn(global.Date, 'now').mockImplementation(() => new Date('2020-03-14T11:01:58.135Z').valueOf());
// To change touch support
jest.mock('../../utils/dom');
describe('Chat component', () => {
afterEach(() => {
// Reset touch support
dom.hasTouchSupport = false;
});
it('should display', () => {
const { asFragment } = render(
<Chat
scrollToBottom={() => {}}
focusChat={false}
userId="foo"
username="user"
showNotice={() => {}}
clearActivities={() => {}}
sendEncryptedMessage={() => {}}
translations={{}}
/>,
);
expect(asFragment()).toMatchSnapshot();
});
it('can send message', () => {
const sendEncryptedMessage = jest.fn();
render(
<Chat
scrollToBottom={() => {}}
focusChat={false}
userId="foo"
username="user"
showNotice={() => {}}
clearActivities={() => {}}
sendEncryptedMessage={sendEncryptedMessage}
translations={translations}
/>,
);
const textarea = screen.getByPlaceholderText(translations.typePlaceholder);
// Validate but without text
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(sendEncryptedMessage).not.toHaveBeenCalled();
// Type test
fireEvent.change(textarea, { target: { value: 'test' } });
// Validate
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(sendEncryptedMessage).toHaveBeenLastCalledWith({
payload: { text: 'test', timestamp: 1584183718135 },
type: 'TEXT_MESSAGE',
});
// Validate (textarea should be empty)
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(sendEncryptedMessage).toHaveBeenCalledTimes(1);
});
it("shouldn't send message with Shift+enter", () => {
const sendEncryptedMessage = jest.fn();
render(
<Chat
scrollToBottom={() => {}}
focusChat={false}
userId="foo"
username="user"
showNotice={() => {}}
clearActivities={() => {}}
sendEncryptedMessage={sendEncryptedMessage}
translations={translations}
/>,
);
const textarea = screen.getByPlaceholderText(translations.typePlaceholder);
// Test shift effect
fireEvent.change(textarea, { target: { value: 'test2' } });
fireEvent.keyDown(textarea, { key: 'Shift' });
fireEvent.keyDown(textarea, { key: 'Enter' });
fireEvent.keyUp(textarea, { key: 'Shift' });
expect(sendEncryptedMessage).toHaveBeenCalledTimes(0);
// Now we want to send the message
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(sendEncryptedMessage).toHaveBeenCalledTimes(1);
expect(sendEncryptedMessage).toHaveBeenLastCalledWith({
payload: { text: 'test2', timestamp: 1584183718135 },
type: 'TEXT_MESSAGE',
});
});
it('should send commands', () => {
const sendEncryptedMessage = jest.fn();
const showNotice = jest.fn();
const clearActivities = jest.fn();
render(
<Chat
scrollToBottom={() => {}}
focusChat={false}
userId="foo"
username="user"
showNotice={showNotice}
clearActivities={clearActivities}
sendEncryptedMessage={sendEncryptedMessage}
translations={translations}
/>,
);
const textarea = screen.getByPlaceholderText(translations.typePlaceholder);
// Test /help
fireEvent.change(textarea, { target: { value: '/help' } });
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(showNotice).toHaveBeenLastCalledWith({
level: 'info',
message: 'Valid commands: /clear, /help, /me, /nick',
});
// Test /me
fireEvent.change(textarea, { target: { value: '/me' } });
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(sendEncryptedMessage).not.toHaveBeenCalled();
fireEvent.change(textarea, { target: { value: '/me action' } });
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(sendEncryptedMessage).toHaveBeenLastCalledWith({
payload: { action: 'action' },
type: 'USER_ACTION',
});
// Test /clear
fireEvent.change(textarea, { target: { value: '/clear' } });
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(clearActivities).toHaveBeenLastCalledWith();
// Test /nick/clear
fireEvent.change(textarea, { target: { value: '/nick john!Th3Ripp&3r' } });
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(sendEncryptedMessage).toHaveBeenLastCalledWith({
payload: { currentUsername: 'user', id: 'foo', newUsername: 'john-Th3Ripp-3r' },
type: 'CHANGE_USERNAME',
});
// Test /nick
fireEvent.change(textarea, { target: { value: '/nick' } });
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(showNotice).toHaveBeenLastCalledWith({
level: 'error',
message: 'Username cannot be blank, Username must start with a letter',
});
// Test /nick
fireEvent.change(textarea, { target: { value: '/nick 3po' } });
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(showNotice).toHaveBeenLastCalledWith({
level: 'error',
message: 'Username must start with a letter',
});
// Test /nick
fireEvent.change(textarea, {
target: { value: '/nick 3po3ralotsofcrapscharactersforyourpleasureandnotmine' },
});
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(sendEncryptedMessage).toHaveBeenLastCalledWith({
payload: { currentUsername: 'user', id: 'foo', newUsername: 'john-Th3Ripp-3r' },
type: 'CHANGE_USERNAME',
});
// Test badcommand
fireEvent.change(textarea, { target: { value: '/void' } });
fireEvent.keyDown(textarea, { key: 'Enter' });
});
it('should work with touch support', () => {
// Enable touch support
dom.hasTouchSupport = true;
jest.mock('../../utils/dom', () => {
return {
getSelectedText: jest.fn(),
hasTouchSupport: true,
};
});
const sendEncryptedMessage = jest.fn();
const { getByTitle } = render(
<Chat
scrollToBottom={() => {}}
focusChat={false}
userId="foo"
username="user"
showNotice={() => {}}
clearActivities={() => {}}
sendEncryptedMessage={sendEncryptedMessage}
translations={translations}
/>,
);
const textarea = screen.getByPlaceholderText(translations.typePlaceholder);
// Type test
fireEvent.change(textarea, { target: { value: 'test' } });
// Touch send button
fireEvent.click(getByTitle('Send'));
expect(sendEncryptedMessage).toHaveBeenLastCalledWith({
payload: { text: 'test', timestamp: 1584183718135 },
type: 'TEXT_MESSAGE',
});
// Should not send message
fireEvent.click(getByTitle('Send'));
expect(sendEncryptedMessage).toHaveBeenCalledTimes(1);
});
});

View File

@ -1,3 +1,50 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Chat Component 1`] = `ReactWrapper {}`;
exports[`Chat component should display 1`] = `
<DocumentFragment>
<form
class="chat-preflight-container"
>
<textarea
class="chat"
rows="1"
/>
<div
class="input-controls"
>
<div
class="styles icon file-transfer btn btn-link"
>
<input
id="fileInput"
name="fileUploader"
placeholder="Choose a file..."
type="file"
/>
<label
for="fileInput"
>
<svg
fill="none"
height="24"
stroke="#fff"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"
/>
<polyline
points="13 2 13 9 20 9"
/>
</svg>
</label>
</div>
</div>
</form>
</DocumentFragment>
`;

View File

@ -1,284 +1,7 @@
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import sanitizeHtml from 'sanitize-html'
import FileTransfer from 'components/FileTransfer'
import { CornerDownRight } from 'react-feather'
import Chat from './Chat'
import { connect } from 'react-redux'
import { clearActivities, showNotice, sendEncryptedMessage } from '../../actions'
import { getSelectedText, hasTouchSupport } from '../../utils/dom'
// Disable for now
// import autosize from 'autosize'
export class Chat extends Component {
constructor(props) {
super(props)
this.state = {
message: '',
touchSupport: hasTouchSupport,
shiftKeyDown: false,
}
this.commands = [{
command: 'nick',
description: 'Changes nickname.',
paramaters: ['{username}'],
usage: '/nick {username}',
scope: 'global',
action: (params) => { // eslint-disable-line
let newUsername = params.join(' ') || '' // eslint-disable-line
// Remove things that arent digits or chars
newUsername = newUsername.replace(/[^A-Za-z0-9]/g, '-')
const errors = []
if (!newUsername.trim().length) {
errors.push('Username cannot be blank')
}
if (newUsername.toString().length > 16) {
errors.push('Username cannot be greater than 16 characters')
}
if (!newUsername.match(/^[A-Z]/i)) {
errors.push('Username must start with a letter')
}
if (errors.length) {
return this.props.showNotice({
message: `${errors.join(', ')}`,
level: 'error',
})
}
this.props.sendEncryptedMessage({
type: 'CHANGE_USERNAME',
payload: {
id: this.props.userId,
newUsername,
currentUsername: this.props.username,
},
})
},
}, {
command: 'help',
description: 'Shows a list of commands.',
paramaters: [],
usage: '/help',
scope: 'local',
action: (params) => { // eslint-disable-line
const validCommands = this.commands.map(command => `/${command.command}`)
this.props.showNotice({
message: `Valid commands: ${validCommands.sort().join(', ')}`,
level: 'info',
})
},
}, {
command: 'me',
description: 'Invoke virtual action',
paramaters: ['{action}'],
usage: '/me {action}',
scope: 'global',
action: (params) => { // eslint-disable-line
const actionMessage = params.join(' ')
if (!actionMessage.trim().length) {
return false
}
this.props.sendEncryptedMessage({
type: 'USER_ACTION',
payload: {
action: actionMessage,
},
})
},
}, {
command: 'clear',
description: 'Clears the chat screen',
paramaters: [],
usage: '/clear',
scope: 'local',
action: (params = null) => { // eslint-disable-line
this.props.clearActivities()
},
}]
}
componentDidMount() {
if (!hasTouchSupport) {
// Disable for now due to vary issues:
// Paste not working, shift+enter line breaks
// autosize(this.textInput);
this.textInput.addEventListener('autosize:resized', () => {
this.props.scrollToBottom()
})
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.focusChat) {
if (!getSelectedText()) {
// Don't focus for now, evaulate UX benfits
// this.textInput.focus()
}
}
}
componentDidUpdate(nextProps, nextState) {
if (!nextState.message.trim().length) {
// autosize.update(this.textInput)
}
}
handleKeyUp(e) {
if (e.key === 'Shift') {
this.setState({
shiftKeyDown: false,
})
}
}
handleKeyPress(e) {
if (e.key === 'Shift') {
this.setState({
shiftKeyDown: true,
})
}
// Fix when autosize is enabled - line breaks require shift+enter twice
if (e.key === 'Enter' && !hasTouchSupport && !this.state.shiftKeyDown) {
e.preventDefault()
if (this.canSend()) {
this.sendMessage()
} else {
this.setState({
message: '',
})
}
}
}
executeCommand(command) {
const commandToExecute = this.commands.find(cmnd => cmnd.command === command.command)
if (commandToExecute) {
const { params } = command
const commandResult = commandToExecute.action(params)
return commandResult
}
return null
}
handleSendClick() {
this.sendMessage.bind(this)
this.textInput.focus()
}
handleFormSubmit(evt) {
evt.preventDefault()
this.sendMessage()
}
parseCommand(message) {
const commandTrigger = {
command: null,
params: [],
}
if (message.charAt(0) === '/') {
const parsedCommand = message.replace('/', '').split(' ')
commandTrigger.command = sanitizeHtml(parsedCommand[0]) || null
// Get params
if (parsedCommand.length >= 2) {
for (let i = 1; i < parsedCommand.length; i++) {
commandTrigger.params.push(parsedCommand[i])
}
}
return commandTrigger
}
return false
}
sendMessage() {
if (!this.canSend()) {
return
}
const { message } = this.state
const isCommand = this.parseCommand(message)
if (isCommand) {
const res = this.executeCommand(isCommand)
if (res === false) {
return
}
} else {
this.props.sendEncryptedMessage({
type: 'TEXT_MESSAGE',
payload: {
text: message,
timestamp: Date.now(),
},
})
}
this.setState({
message: '',
})
}
handleInputChange(evt) {
this.setState({
message: evt.target.value,
})
}
canSend() {
return this.state.message.trim().length
}
render() {
const touchSupport = this.state.touchSupport
return (
<form onSubmit={this.handleFormSubmit.bind(this)} className="chat-preflight-container">
<textarea
rows="1"
onKeyUp={this.handleKeyUp.bind(this)}
onKeyDown={this.handleKeyPress.bind(this)}
ref={(input) => { this.textInput = input }}
autoFocus
className="chat"
value={this.state.message}
placeholder={this.props.translations.typePlaceholder}
onChange={this.handleInputChange.bind(this)} />
<div className="input-controls">
<FileTransfer sendEncryptedMessage={this.props.sendEncryptedMessage} />
{touchSupport &&
<button onClick={this.handleSendClick.bind(this)} className={`icon is-right send btn btn-link ${this.canSend() ? 'active' : ''}`}>
<CornerDownRight className={this.canSend() ? '' : 'disabled'} />
</button>
}
</div>
</form>
)
}
}
Chat.propTypes = {
sendEncryptedMessage: PropTypes.func.isRequired,
showNotice: PropTypes.func.isRequired,
userId: PropTypes.string.isRequired,
username: PropTypes.string.isRequired,
clearActivities: PropTypes.func.isRequired,
focusChat: PropTypes.bool.isRequired,
scrollToBottom: PropTypes.func.isRequired,
translations: PropTypes.object.isRequired,
}
const mapStateToProps = state => ({
username: state.user.username,

View File

@ -0,0 +1,9 @@
import React from 'react'
import { render } from '@testing-library/react'
import Connecting from '.'
test('Connecting component is displaying', async () => {
const {asFragment} = render(<Connecting />)
expect(asFragment()).toMatchSnapshot()
})

View File

@ -0,0 +1,9 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Connecting component is displaying 1`] = `
<DocumentFragment>
<div>
Please wait while we secure a connection to Darkwire...
</div>
</DocumentFragment>
`;

View File

@ -0,0 +1,90 @@
import React from 'react';
import { render, screen, fireEvent, createEvent } from '@testing-library/react';
import FileTransfer from '.';
test('FileTransfer component is displaying', async () => {
const { asFragment } = render(<FileTransfer sendEncryptedMessage={() => {}} />);
expect(asFragment()).toMatchSnapshot();
});
// Skipped as broken in this component version. Should be fixed later.
test.skip('FileTransfer component detect bad browser support', async () => {
const { File } = window;
// Remove one of component dependency
delete window.File;
const { asFragment } = render(<FileTransfer sendEncryptedMessage={() => {}} />);
expect(asFragment()).toMatchSnapshot();
window.File = File;
});
test('Try to send file', async done => {
const sendEncryptedMessage = data => {
try {
expect(data).toMatchObject({
payload: { encodedFile: 'dGV4dGZpbGU=', fileName: 'filename-png', fileType: 'text/plain' },
type: 'SEND_FILE',
});
done();
} catch (error) {
done(error);
}
};
render(<FileTransfer sendEncryptedMessage={sendEncryptedMessage} />);
const input = screen.getByPlaceholderText('Choose a file...');
const testFile = new File(['textfile'], 'filename.png', { type: 'text/plain' });
// Fire change event
fireEvent.change(input, { target: { files: [testFile] } });
});
test('Try to send no file', async () => {
render(<FileTransfer sendEncryptedMessage={() => {}} />);
const input = screen.getByPlaceholderText('Choose a file...');
// Fire change event
fireEvent.change(input, { target: { files: [] } });
});
test('Try to send unsupported file', async () => {
window.alert = jest.fn();
render(<FileTransfer sendEncryptedMessage={() => {}} />);
const input = screen.getByPlaceholderText('Choose a file...');
const testFile = new File(['textfile'], 'filename.fake', { type: 'text/plain' });
// Create thange event with fake file
const changeEvent = createEvent.change(input, { target: { files: [testFile] } });
// Fire change event
fireEvent(input, changeEvent);
expect(window.alert).toHaveBeenCalledWith('File type not supported');
});
test('Try to send too big file', async () => {
window.alert = jest.fn();
render(<FileTransfer sendEncryptedMessage={() => {}} />);
const input = screen.getByPlaceholderText('Choose a file...');
var fileContent = new Uint8Array(4000001);
const testFile = new File([fileContent], 'filename.png', { type: 'text/plain' });
// Fire change event
fireEvent.change(input, { target: { files: [testFile] } });
expect(window.alert).toHaveBeenCalledWith('Max filesize is 4MB');
});

View File

@ -0,0 +1,38 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`FileTransfer component is displaying 1`] = `
<DocumentFragment>
<div
class="styles icon file-transfer btn btn-link"
>
<input
id="fileInput"
name="fileUploader"
placeholder="Choose a file..."
type="file"
/>
<label
for="fileInput"
>
<svg
fill="none"
height="24"
stroke="#fff"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"
/>
<polyline
points="13 2 13 9 20 9"
/>
</svg>
</label>
</div>
</DocumentFragment>
`;

View File

@ -102,7 +102,7 @@ export default class FileTransfer extends Component {
}
return (
<div className={`${styles} icon file-transfer btn btn-link`}>
<input type="file" name="fileUploader" id="fileInput" ref={c => this._fileInput = c} />
<input placeholder="Choose a file..." type="file" name="fileUploader" id="fileInput" ref={c => this._fileInput = c} />
<label htmlFor="fileInput">
<File color="#fff" />
</label>

View File

@ -0,0 +1,201 @@
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Activity from './Activity';
import { Provider } from 'react-redux';
import configureStore from 'store';
const store = configureStore();
//jest.mock('components/T'); // Need store
describe('Activity component', () => {
it('should display', () => {
const activity = {
type: '',
};
const { asFragment } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should display TEXT_MESSAGE', () => {
const activity = {
type: 'TEXT_MESSAGE',
username: 'alice',
timestamp: new Date('2020-03-14T11:01:58.135Z').valueOf(),
text: 'Hi!',
};
const { asFragment } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should display USER_ENTER', () => {
const activity = {
type: 'USER_ENTER',
username: 'alice',
};
const { asFragment } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should display USER_EXIT', () => {
const activity = {
type: 'USER_EXIT',
username: 'alice',
};
const { asFragment } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should display TOGGLE_LOCK_ROOM', () => {
const activity = {
type: 'TOGGLE_LOCK_ROOM',
locked: true,
username: 'alice',
};
const { asFragment, rerender } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
activity.locked = false;
rerender(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should display NOTICE', () => {
const activity = {
type: 'NOTICE',
message: 'Hello world!',
};
const { asFragment } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should display CHANGE_USERNAME', () => {
const activity = {
type: 'CHANGE_USERNAME',
currentUsername: 'alice',
newUsername: 'alicette',
};
const { asFragment } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should display USER_ACTION', () => {
const activity = {
type: 'USER_ACTION',
username: 'alice',
action: 'did right!',
};
const { asFragment } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should display RECEIVE_FILE', () => {
const activity = {
type: 'RECEIVE_FILE',
username: 'alice',
fileName: 'alice.pdf',
encodedFile: 'dGV4dGZpbGU=',
fileType: 'text/plain',
};
global.URL.createObjectURL = jest.fn(data => `url:${data}`);
const { asFragment } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should display RECEIVE_FILE with image', () => {
global.URL.createObjectURL = jest.fn(data => `url:${data}`);
const mockScrollToBottom = jest.fn();
const activity = {
type: 'RECEIVE_FILE',
username: 'alice',
fileName: 'alice.jpg',
encodedFile: 'dGV4dGZpbGU=',
fileType: 'image/jpg',
};
const { asFragment, getByAltText } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={mockScrollToBottom} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
const image = getByAltText('alice.jpg from alice');
fireEvent.load(image);
expect(mockScrollToBottom).toHaveBeenCalled();
});
it('should display SEND_FILE', () => {
global.URL.createObjectURL = jest.fn(data => `url:${data}`);
const activity = {
type: 'SEND_FILE',
username: 'alice',
fileName: 'alice.pdf',
encodedFile: 'dGV4dGZpbGU=',
fileType: 'text/plain',
};
const { asFragment } = render(
<Provider store={store}>
<Activity activity={activity} scrollToBottom={jest.fn()} />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
});

View File

@ -72,7 +72,7 @@ class ActivityList extends Component {
render() {
return (
<div className="main-chat">
<div onClick={this.handleChatClick.bind(this)} className="message-stream h-100" ref={el => this.messageStream = el}>
<div onClick={this.handleChatClick.bind(this)} className="message-stream h-100" ref={el => this.messageStream = el} data-testid="main-div">
<ul className="plain" ref={el => this.activitiesList = el}>
<li><p className={styles.tos}><button className='btn btn-link' onClick={this.props.openModal.bind(this, 'About')}> <T path='agreement'/></button></p></li>
{this.props.activities.map((activity, index) => (

View File

@ -0,0 +1,160 @@
import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react';
import ActivityList from './ActivityList';
import { Provider } from 'react-redux';
import configureStore from 'store';
const store = configureStore();
jest.useFakeTimers();
describe('ActivityList component', () => {
it('should display', () => {
const { asFragment } = render(
<Provider store={store}>
<ActivityList openModal={jest.fn()} activities={[]} setScrolledToBottom={jest.fn()} scrolledToBottom />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should display with activities', () => {
const activities = [
{
type: 'TEXT_MESSAGE',
username: 'alice',
timestamp: new Date('2020-03-14T11:01:58.135Z').valueOf(),
text: 'Hi!',
},
{
type: 'USER_ENTER',
username: 'alice',
},
{
type: 'CHANGE_USERNAME',
currentUsername: 'alice',
newUsername: 'alicette',
},
];
const { asFragment } = render(
<Provider store={store}>
<ActivityList openModal={jest.fn()} activities={activities} setScrolledToBottom={jest.fn()} scrolledToBottom />
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should show About modal', async () => {
const mockOpenModal = jest.fn();
const { getByText } = render(
<Provider store={store}>
<ActivityList openModal={mockOpenModal} activities={[]} setScrolledToBottom={jest.fn()} scrolledToBottom />
</Provider>,
);
fireEvent.click(getByText('By using Darkwire, you are agreeing to our Acceptable Use Policy and Terms of Service'));
jest.runAllTimers();
expect(mockOpenModal.mock.calls[0][0]).toBe('About');
});
it('should focus chat', () => {
const { getByTestId } = render(
<Provider store={store}>
<ActivityList openModal={jest.fn()} activities={[]} setScrolledToBottom={jest.fn()} scrolledToBottom />
</Provider>,
);
fireEvent.click(getByTestId('main-div'));
jest.runAllTimers();
});
it('should handle scroll', () => {
const mockSetScrollToBottom = jest.fn();
jest
.spyOn(Element.prototype, 'clientHeight', 'get')
.mockReturnValueOnce(400)
.mockReturnValueOnce(200)
.mockReturnValueOnce(400)
.mockReturnValueOnce(200);
Element.prototype.getBoundingClientRect = jest
.fn()
.mockReturnValueOnce({ top: 0 })
.mockReturnValueOnce({ top: 60 })
.mockReturnValueOnce({ top: 0 })
.mockReturnValueOnce({ top: 261 });
const { getByTestId, rerender } = render(
<Provider store={store}>
<ActivityList
openModal={jest.fn()}
activities={[]}
setScrolledToBottom={mockSetScrollToBottom}
scrolledToBottom={false}
/>
</Provider>,
);
fireEvent.scroll(getByTestId('main-div'));
expect(mockSetScrollToBottom).toHaveBeenLastCalledWith(true);
rerender(
<Provider store={store}>
<ActivityList
openModal={jest.fn()}
activities={[]}
setScrolledToBottom={mockSetScrollToBottom}
scrolledToBottom={true}
/>
</Provider>,
);
fireEvent.scroll(getByTestId('main-div'));
expect(mockSetScrollToBottom).toHaveBeenCalledTimes(2);
expect(mockSetScrollToBottom).toHaveBeenLastCalledWith(false);
});
it('should scroll to bottom on new message', () => {
const mockSetScrollToBottom = jest.fn();
jest.spyOn(Element.prototype, 'scrollHeight', 'get').mockReturnValue(42);
const mockScrollTop = jest.spyOn(Element.prototype, 'scrollTop', 'set');
const { rerender } = render(
<Provider store={store}>
<ActivityList
openModal={jest.fn()}
activities={[]}
setScrolledToBottom={mockSetScrollToBottom}
scrolledToBottom={true}
/>
</Provider>,
);
rerender(
<Provider store={store}>
<ActivityList
openModal={jest.fn()}
activities={[
{
type: 'TEXT_MESSAGE',
username: 'alice',
timestamp: new Date('2020-03-14T11:01:58.135Z').valueOf(),
text: 'Hi!',
},
]}
setScrolledToBottom={mockSetScrollToBottom}
scrolledToBottom={true}
/>
</Provider>,
);
jest.runAllTimers();
expect(mockScrollTop).toHaveBeenLastCalledWith(42);
});
});

View File

@ -249,6 +249,7 @@ Home.defaultProps = {
Home.propTypes = {
receiveEncryptedMessage: PropTypes.func.isRequired,
receiveUnencryptedMessage: PropTypes.func.isRequired,
createUser: PropTypes.func.isRequired,
activities: PropTypes.array.isRequired,
username: PropTypes.string.isRequired,

View File

@ -0,0 +1,73 @@
import React from 'react';
import { render } from '@testing-library/react';
import Home from './Home';
import { Provider } from 'react-redux';
import configureStore from 'store';
const store = configureStore();
jest.mock('react-modal'); // Cant load modal without root app element
jest.mock('utils/socket', () => {
// Avoid exception
return {
connect: jest.fn().mockImplementation(() => {
return {
on: jest.fn(),
emit: jest.fn(),
};
}),
};
}); //
jest.mock('utils/crypto', () => {
// Need window.crytpo.subtle
return jest.fn().mockImplementation(() => {
return {
createEncryptDecryptKeys: () => {
return {
privateKey: 'private',
publicKey: 'public',
};
},
exportKey: () => {
return 'exportedkey';
},
};
});
});
test('Home component is displaying', async () => {
const { asFragment } = render(
<Provider store={store}>
<Home
translations={{}}
members={[]}
openModal={() => {}}
activities={[]}
match={{ params: { roomId: 'roomTest' } }}
createUser={() => {}}
toggleSocketConnected={() => {}}
receiveEncryptedMessage={() => {}}
receiveUnencryptedMessage={() => {}}
scrolledToBottom={true}
setScrolledToBottom={() => {}}
iAmOwner={true}
roomLocked={false}
userId={'userId'}
roomId={'testId'}
sendEncryptedMessage={() => {}}
sendUnencryptedMessage={() => {}}
socketConnected={false}
toggleSoundEnabled={() => {}}
soundIsEnabled={false}
faviconCount={0}
toggleWindowFocus={() => {}}
closeModal={() => {}}
publicKey={{}}
username={'linus'}
/>
</Provider>,
);
expect(asFragment()).toMatchSnapshot();
});

View File

@ -0,0 +1,269 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Activity component should display 1`] = `<DocumentFragment />`;
exports[`Activity component should display CHANGE_USERNAME 1`] = `
<DocumentFragment>
<div>
<div
class="info"
>
<div>
<span>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
changed their name to
<span
class="username"
style="color: rgb(235, 162, 242);"
>
alicette
</span>
</span>
</div>
</div>
</div>
</DocumentFragment>
`;
exports[`Activity component should display NOTICE 1`] = `
<DocumentFragment>
<div>
<div
class="info"
>
<div>
Hello world!
</div>
</div>
</div>
</DocumentFragment>
`;
exports[`Activity component should display RECEIVE_FILE 1`] = `
<DocumentFragment>
<div>
<span>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
sent you a file.
</span>
 
<a
download="alice.pdf"
href="url:[object Blob]"
rel="noopener noreferrer"
target="_blank"
>
<span>
Download alice.pdf
</span>
</a>
</div>
</DocumentFragment>
`;
exports[`Activity component should display RECEIVE_FILE with image 1`] = `
<DocumentFragment>
<div>
<span>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
sent you a file.
</span>
 
<a
download="alice.jpg"
href="url:[object Blob]"
rel="noopener noreferrer"
target="_blank"
>
<span>
Download alice.jpg
</span>
</a>
<img
alt="alice.jpg from alice"
class="image-transfer zoomable"
src="data:image/jpg;base64,dGV4dGZpbGU="
/>
</div>
</DocumentFragment>
`;
exports[`Activity component should display SEND_FILE 1`] = `
<DocumentFragment>
<div>
<div
class="info"
>
<div>
<span>
You sent
<a
download="alice.pdf"
href="url:[object Blob]"
rel="noopener noreferrer"
target="_blank"
>
alice.pdf
</a>
</span>
 
</div>
</div>
</div>
</DocumentFragment>
`;
exports[`Activity component should display TEXT_MESSAGE 1`] = `
<DocumentFragment>
<div>
<div
class="chat-meta"
>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
<span
class="muted timestamp"
>
11:01 AM
</span>
</div>
<div
class="chat"
>
<span
class="Linkify"
>
Hi!
</span>
</div>
</div>
</DocumentFragment>
`;
exports[`Activity component should display TOGGLE_LOCK_ROOM 1`] = `
<DocumentFragment>
<div>
<div
class="info"
>
<div>
<span>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
locked the room
</span>
</div>
</div>
</div>
</DocumentFragment>
`;
exports[`Activity component should display TOGGLE_LOCK_ROOM 2`] = `
<DocumentFragment>
<div>
<div
class="info"
>
<div>
<span>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
unlocked the room
</span>
</div>
</div>
</div>
</DocumentFragment>
`;
exports[`Activity component should display USER_ACTION 1`] = `
<DocumentFragment>
<div>
<div
class="info"
>
<div>
*
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
did right!
</div>
</div>
</div>
</DocumentFragment>
`;
exports[`Activity component should display USER_ENTER 1`] = `
<DocumentFragment>
<div>
<div
class="info"
>
<div>
<span>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
joined
</span>
</div>
</div>
</div>
</DocumentFragment>
`;
exports[`Activity component should display USER_EXIT 1`] = `
<DocumentFragment>
<div>
<div
class="info"
>
<div>
<span>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
left
</span>
</div>
</div>
</div>
</DocumentFragment>
`;

View File

@ -0,0 +1,235 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ActivityList component should display 1`] = `
<DocumentFragment>
<div
class="main-chat"
>
<div
class="message-stream h-100"
data-testid="main-div"
>
<ul
class="plain"
>
<li>
<p
class="tos"
>
<button
class="btn btn-link"
>
By using Darkwire, you are agreeing to our Acceptable Use Policy and Terms of Service
</button>
</p>
</li>
</ul>
</div>
<div
class="chat-container"
>
<form
class="chat-preflight-container"
>
<textarea
class="chat"
placeholder="Type here"
rows="1"
/>
<div
class="input-controls"
>
<div
class="styles icon file-transfer btn btn-link"
>
<input
id="fileInput"
name="fileUploader"
placeholder="Choose a file..."
type="file"
/>
<label
for="fileInput"
>
<svg
fill="none"
height="24"
stroke="#fff"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"
/>
<polyline
points="13 2 13 9 20 9"
/>
</svg>
</label>
</div>
</div>
</form>
</div>
</div>
</DocumentFragment>
`;
exports[`ActivityList component should display with activities 1`] = `
<DocumentFragment>
<div
class="main-chat"
>
<div
class="message-stream h-100"
data-testid="main-div"
>
<ul
class="plain"
>
<li>
<p
class="tos"
>
<button
class="btn btn-link"
>
By using Darkwire, you are agreeing to our Acceptable Use Policy and Terms of Service
</button>
</p>
</li>
<li
class="activity-item TEXT_MESSAGE"
>
<div>
<div
class="chat-meta"
>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
<span
class="muted timestamp"
>
11:01 AM
</span>
</div>
<div
class="chat"
>
<span
class="Linkify"
>
Hi!
</span>
</div>
</div>
</li>
<li
class="activity-item USER_ENTER"
>
<div>
<div
class="info"
>
<div>
<span>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
joined
</span>
</div>
</div>
</div>
</li>
<li
class="activity-item CHANGE_USERNAME"
>
<div>
<div
class="info"
>
<div>
<span>
<span
class="username"
style="color: rgb(204, 241, 255);"
>
alice
</span>
changed their name to
<span
class="username"
style="color: rgb(235, 162, 242);"
>
alicette
</span>
</span>
</div>
</div>
</div>
</li>
</ul>
</div>
<div
class="chat-container"
>
<form
class="chat-preflight-container"
>
<textarea
class="chat"
placeholder="Type here"
rows="1"
/>
<div
class="input-controls"
>
<div
class="styles icon file-transfer btn btn-link"
>
<input
id="fileInput"
name="fileUploader"
placeholder="Choose a file..."
type="file"
/>
<label
for="fileInput"
>
<svg
fill="none"
height="24"
stroke="#fff"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"
/>
<polyline
points="13 2 13 9 20 9"
/>
</svg>
</label>
</div>
</div>
</form>
</div>
</div>
</DocumentFragment>
`;

View File

@ -0,0 +1,365 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Home component is displaying 1`] = `
<DocumentFragment>
<div
class="styles h-100"
>
<div
class="nav-container"
>
<div
class="alert-banner"
>
<span
class="icon"
>
<svg
fill="none"
height="15"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="15"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="12"
cy="12"
r="10"
/>
<line
x1="12"
x2="12"
y1="8"
y2="12"
/>
<line
x1="12"
x2="12"
y1="16"
y2="16"
/>
</svg>
</span>
<span>
Disconnected
</span>
</div>
<nav
class="navbar navbar-expand-md navbar-dark"
>
<div
class="meta"
>
<img
alt="Darkwire"
class="logo"
src="logo.png"
/>
<button
class="btn btn-plain btn-link clipboard-trigger room-id ellipsis"
data-clipboard-text="http://localhost/testId"
data-placement="bottom"
data-toggle="tooltip"
>
/testId
</button>
<span
class="lock-room-container"
>
<button
class="lock-room btn btn-link btn-plain"
data-placement="bottom"
data-toggle="tooltip"
title="You must be the owner to lock or unlock the room"
>
<svg
class="muted"
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<rect
height="11"
rx="2"
ry="2"
width="18"
x="3"
y="11"
/>
<path
d="M7 11V7a5 5 0 0 1 9.9-1"
/>
</svg>
</button>
</span>
<div
class="dropdown members-dropdown"
>
<a
class="dropdown__trigger "
>
<button
class="btn btn-link btn-plain members-action"
title="Users"
>
<svg
class="users-icon"
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"
/>
<circle
cx="9"
cy="7"
r="4"
/>
<path
d="M23 21v-2a4 4 0 0 0-3-3.87"
/>
<path
d="M16 3.13a4 4 0 0 1 0 7.75"
/>
</svg>
</button>
<span>
0
</span>
</a>
<div
class="dropdown__content "
>
<ul
class="plain"
/>
</div>
</div>
</div>
<button
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
class="navbar-toggler"
data-target="#navbarSupportedContent"
data-toggle="collapse"
type="button"
>
<span
class="navbar-toggler-icon"
/>
</button>
<div
class="collapse navbar-collapse"
id="navbarSupportedContent"
>
<ul
class="navbar-nav ml-auto"
>
<li
class="nav-item"
>
<button
class="btn btn-plain nav-link"
target="blank"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="12"
cy="12"
r="10"
/>
<line
x1="12"
x2="12"
y1="8"
y2="16"
/>
<line
x1="8"
x2="16"
y1="12"
y2="12"
/>
</svg>
<span />
</button>
</li>
<li
class=" nav-item"
>
<button
class="btn btn-plain nav-link"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="12"
cy="12"
r="3"
/>
<path
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"
/>
</svg>
<span />
</button>
</li>
<li
class="nav-item"
>
<button
class="btn btn-plain nav-link"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="12"
cy="12"
r="10"
/>
<line
x1="12"
x2="12"
y1="16"
y2="12"
/>
<line
x1="12"
x2="12"
y1="8"
y2="8"
/>
</svg>
<span />
</button>
</li>
</ul>
</div>
</nav>
</div>
<div
class="main-chat"
>
<div
class="message-stream h-100"
data-testid="main-div"
>
<ul
class="plain"
>
<li>
<p
class="tos"
>
<button
class="btn btn-link"
>
By using Darkwire, you are agreeing to our Acceptable Use Policy and Terms of Service
</button>
</p>
</li>
</ul>
</div>
<div
class="chat-container"
>
<form
class="chat-preflight-container"
>
<textarea
class="chat"
placeholder="Type here"
rows="1"
/>
<div
class="input-controls"
>
<div
class="styles icon file-transfer btn btn-link"
>
<input
id="fileInput"
name="fileUploader"
placeholder="Choose a file..."
type="file"
/>
<label
for="fileInput"
>
<svg
fill="none"
height="24"
stroke="#fff"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"
/>
<polyline
points="13 2 13 9 20 9"
/>
</svg>
</label>
</div>
</div>
</form>
</div>
</div>
</div>
</DocumentFragment>
`;

View File

@ -0,0 +1,15 @@
import React from 'react';
import { render } from '@testing-library/react';
import Message from '.';
test('Message component is displaying', async () => {
const { asFragment } = render(
<Message
sender={'linus'}
timestamp={1588794269074}
message={'we come in peace'}
/>
);
expect(asFragment()).toMatchSnapshot();
});

View File

@ -0,0 +1,32 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Message component is displaying 1`] = `
<DocumentFragment>
<div>
<div
class="chat-meta"
>
<span
class="username"
style="color: rgb(131, 239, 135);"
>
linus
</span>
<span
class="muted timestamp"
>
7:44 PM
</span>
</div>
<div
class="chat"
>
<span
class="Linkify"
>
we come in peace
</span>
</div>
</div>
</DocumentFragment>
`;

View File

@ -0,0 +1,303 @@
import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react';
import Nav from '.';
import mock$ from 'jquery';
const mockTooltip = jest.fn().mockImplementation(param => {
// console.log('tooltip', param);
});
const mockCollapse = jest.fn().mockImplementation(param => {
// console.log('collapse', param);
});
jest.mock('jquery', () => {
return jest.fn().mockImplementation(param => {
// console.log('$', param);
if (typeof param === 'function') {
param();
}
return {
tooltip: mockTooltip,
collapse: mockCollapse,
};
});
});
jest.mock('shortid', () => {
return {
generate() {
return 'fakeid';
},
};
});
jest.useFakeTimers();
const mockTranslations = {
newRoomButton: 'new room',
settingsButton: 'settings',
aboutButton: 'about',
};
test('Nav component is displaying', async () => {
const { asFragment } = render(
<Nav
members={[]}
roomId={'testRoom'}
userId={'userId__'}
roomLocked={false}
toggleLockRoom={() => {}}
openModal={() => {}}
iAmOwner={true}
translations={{}}
/>,
);
expect(asFragment()).toMatchSnapshot();
expect(mock$).toHaveBeenCalledWith('.room-id');
expect(mock$).toHaveBeenLastCalledWith('.lock-room');
expect(mockTooltip).toHaveBeenLastCalledWith({ trigger: 'manual' });
});
test('Nav component is displaying with another configuration and can rerender', async () => {
const { asFragment, rerender } = render(
<Nav
members={[
{ id: 'id1', username: 'alan', isOwner: true },
{ id: 'id2', username: 'dan', isOwner: false },
]}
roomId={'testRoom_2'}
userId={'userId_2'}
roomLocked={true}
toggleLockRoom={() => {}}
openModal={() => {}}
iAmOwner={false}
translations={{}}
/>,
);
expect(asFragment()).toMatchSnapshot();
rerender(
<Nav
members={[
{ id: 'id1', username: 'alan', isOwner: true },
{ id: 'id2', username: 'dan', isOwner: false },
]}
roomId={'testRoom_3'}
userId={'userId_3'}
roomLocked={true}
toggleLockRoom={() => {}}
openModal={() => {}}
iAmOwner={false}
translations={{}}
/>,
);
expect(mock$).toHaveBeenCalledWith('.me-icon-wrap');
expect(mock$).toHaveBeenLastCalledWith('.owner-icon-wrap');
});
test('Can copy room url', async () => {
document.execCommand = jest.fn(() => true);
const toggleLockRoom = jest.fn();
const { getByText } = render(
<Nav
members={[
{ id: 'id1', username: 'alan', isOwner: true },
{ id: 'id2', username: 'dan', isOwner: false },
]}
roomId={'testRoom'}
userId={'userId'}
roomLocked={true}
toggleLockRoom={toggleLockRoom}
openModal={() => {}}
iAmOwner={false}
translations={{}}
/>,
);
fireEvent.click(getByText(`/testRoom`));
expect(document.execCommand).toHaveBeenLastCalledWith('copy');
expect(mock$).toHaveBeenCalledTimes(15);
expect(mockTooltip).toHaveBeenLastCalledWith('show');
// Wait tooltip closing
jest.runAllTimers();
expect(mock$).toHaveBeenCalledTimes(18);
expect(mockTooltip).toHaveBeenLastCalledWith('hide');
});
test('Can lock/unlock room is room owner only', async () => {
const toggleLockRoom = jest.fn();
const { rerender, getByTitle } = render(
<Nav
members={[
{ id: 'id1', username: 'alan', isOwner: true },
{ id: 'id2', username: 'dan', isOwner: false },
]}
roomId={'testRoom'}
userId={'userId'}
roomLocked={true}
toggleLockRoom={toggleLockRoom}
openModal={() => {}}
iAmOwner={true}
translations={{}}
/>,
);
const toggleLockRoomButton = getByTitle('You must be the owner to lock or unlock the room');
fireEvent.click(toggleLockRoomButton);
expect(toggleLockRoom).toHaveBeenCalledWith();
fireEvent.click(toggleLockRoomButton);
expect(toggleLockRoom).toHaveBeenCalledTimes(2);
// We are not the room owner anymore
rerender(
<Nav
members={[
{ id: 'id1', username: 'alan', isOwner: true },
{ id: 'id2', username: 'dan', isOwner: false },
]}
roomId={'testRoom'}
userId={'userId'}
roomLocked={true}
toggleLockRoom={toggleLockRoom}
openModal={() => {}}
iAmOwner={false}
translations={{}}
/>,
);
fireEvent.click(toggleLockRoomButton);
expect(toggleLockRoom).toHaveBeenCalledTimes(2);
expect(mock$).toHaveBeenLastCalledWith('.lock-room');
expect(mockTooltip).toHaveBeenLastCalledWith('show');
});
test('Can show user list', async () => {
// Test with one user owner and me
const { getByTitle, getByText, queryByTitle, rerender } = render(
<Nav
members={[{ id: 'id1', username: 'alan', isOwner: true }]}
roomId={'testRoom'}
userId={'id1'}
roomLocked={true}
toggleLockRoom={() => {}}
openModal={() => {}}
iAmOwner={true}
translations={{}}
/>,
);
fireEvent.click(getByTitle('Users'));
await waitFor(() => expect(getByText('alan')).toBeInTheDocument());
await waitFor(() => expect(getByTitle('Owner')).toBeInTheDocument());
await waitFor(() => expect(getByTitle('Me')).toBeInTheDocument());
// Test with two user not owner, not me
rerender(
<Nav
members={[
{ id: 'id1', username: 'alan', isOwner: false },
{ id: 'id2', username: 'dan', isOwner: false },
]}
roomId={'testRoom'}
userId={'otherId'}
roomLocked={true}
toggleLockRoom={() => {}}
openModal={() => {}}
iAmOwner={true}
translations={{}}
/>,
);
await waitFor(() => expect(getByText('alan')).toBeInTheDocument());
await waitFor(() => expect(getByText('dan')).toBeInTheDocument());
expect(queryByTitle('Owner')).not.toBeInTheDocument();
expect(queryByTitle('Me')).not.toBeInTheDocument();
});
test('Can open settings', async () => {
const openModal = jest.fn();
// Test with one user owner and me
const { getByText } = render(
<Nav
members={[]}
roomId={'testRoom'}
userId={'id1'}
roomLocked={true}
toggleLockRoom={() => {}}
openModal={openModal}
iAmOwner={true}
translations={mockTranslations}
/>,
);
fireEvent.click(getByText(mockTranslations.settingsButton));
expect(mock$).toHaveBeenLastCalledWith('.navbar-collapse');
expect(mockCollapse).toHaveBeenLastCalledWith('hide');
expect(openModal).toHaveBeenLastCalledWith('Settings');
});
test('Can open About', async () => {
const openModal = jest.fn();
// Test with one user owner and me
const { getByText } = render(
<Nav
members={[]}
roomId={'testRoom'}
userId={'id1'}
roomLocked={true}
toggleLockRoom={() => {}}
openModal={openModal}
iAmOwner={true}
translations={mockTranslations}
/>,
);
fireEvent.click(getByText(mockTranslations.aboutButton));
expect(mock$).toHaveBeenLastCalledWith('.navbar-collapse');
expect(mockCollapse).toHaveBeenLastCalledWith('hide');
expect(openModal).toHaveBeenLastCalledWith('About');
});
test('Can open About', async () => {
window.open = jest.fn();
// Test with one user owner and me
const { getByText } = render(
<Nav
members={[]}
roomId={'testRoom'}
userId={'id1'}
roomLocked={true}
toggleLockRoom={() => {}}
openModal={() => {}}
iAmOwner={true}
translations={mockTranslations}
/>,
);
fireEvent.click(getByText(mockTranslations.newRoomButton));
expect(mock$).toHaveBeenLastCalledWith('.navbar-collapse');
expect(mockCollapse).toHaveBeenLastCalledWith('hide');
expect(window.open).toHaveBeenLastCalledWith('/fakeid');
});

View File

@ -0,0 +1,531 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Nav component is displaying 1`] = `
<DocumentFragment>
<nav
class="navbar navbar-expand-md navbar-dark"
>
<div
class="meta"
>
<img
alt="Darkwire"
class="logo"
src="logo.png"
/>
<button
class="btn btn-plain btn-link clipboard-trigger room-id ellipsis"
data-clipboard-text="http://localhost/testRoom"
data-placement="bottom"
data-toggle="tooltip"
>
/testRoom
</button>
<span
class="lock-room-container"
>
<button
class="lock-room btn btn-link btn-plain"
data-placement="bottom"
data-toggle="tooltip"
title="You must be the owner to lock or unlock the room"
>
<svg
class="muted"
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<rect
height="11"
rx="2"
ry="2"
width="18"
x="3"
y="11"
/>
<path
d="M7 11V7a5 5 0 0 1 9.9-1"
/>
</svg>
</button>
</span>
<div
class="dropdown members-dropdown"
>
<a
class="dropdown__trigger "
>
<button
class="btn btn-link btn-plain members-action"
title="Users"
>
<svg
class="users-icon"
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"
/>
<circle
cx="9"
cy="7"
r="4"
/>
<path
d="M23 21v-2a4 4 0 0 0-3-3.87"
/>
<path
d="M16 3.13a4 4 0 0 1 0 7.75"
/>
</svg>
</button>
<span>
0
</span>
</a>
<div
class="dropdown__content "
>
<ul
class="plain"
/>
</div>
</div>
</div>
<button
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
class="navbar-toggler"
data-target="#navbarSupportedContent"
data-toggle="collapse"
type="button"
>
<span
class="navbar-toggler-icon"
/>
</button>
<div
class="collapse navbar-collapse"
id="navbarSupportedContent"
>
<ul
class="navbar-nav ml-auto"
>
<li
class="nav-item"
>
<button
class="btn btn-plain nav-link"
target="blank"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="12"
cy="12"
r="10"
/>
<line
x1="12"
x2="12"
y1="8"
y2="16"
/>
<line
x1="8"
x2="16"
y1="12"
y2="12"
/>
</svg>
<span />
</button>
</li>
<li
class=" nav-item"
>
<button
class="btn btn-plain nav-link"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="12"
cy="12"
r="3"
/>
<path
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"
/>
</svg>
<span />
</button>
</li>
<li
class="nav-item"
>
<button
class="btn btn-plain nav-link"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="12"
cy="12"
r="10"
/>
<line
x1="12"
x2="12"
y1="16"
y2="12"
/>
<line
x1="12"
x2="12"
y1="8"
y2="8"
/>
</svg>
<span />
</button>
</li>
</ul>
</div>
</nav>
</DocumentFragment>
`;
exports[`Nav component is displaying with another configuration and can rerender 1`] = `
<DocumentFragment>
<nav
class="navbar navbar-expand-md navbar-dark"
>
<div
class="meta"
>
<img
alt="Darkwire"
class="logo"
src="logo.png"
/>
<button
class="btn btn-plain btn-link clipboard-trigger room-id ellipsis"
data-clipboard-text="http://localhost/testRoom_2"
data-placement="bottom"
data-toggle="tooltip"
>
/testRoom_2
</button>
<span
class="lock-room-container"
>
<button
class="lock-room btn btn-link btn-plain"
data-placement="bottom"
data-toggle="tooltip"
title="You must be the owner to lock or unlock the room"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<rect
height="11"
rx="2"
ry="2"
width="18"
x="3"
y="11"
/>
<path
d="M7 11V7a5 5 0 0 1 10 0v4"
/>
</svg>
</button>
</span>
<div
class="dropdown members-dropdown"
>
<a
class="dropdown__trigger "
>
<button
class="btn btn-link btn-plain members-action"
title="Users"
>
<svg
class="users-icon"
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"
/>
<circle
cx="9"
cy="7"
r="4"
/>
<path
d="M23 21v-2a4 4 0 0 0-3-3.87"
/>
<path
d="M16 3.13a4 4 0 0 1 0 7.75"
/>
</svg>
</button>
<span>
2
</span>
</a>
<div
class="dropdown__content "
>
<ul
class="plain"
>
<li>
<span
class="username"
style="color: rgb(192, 202, 249);"
>
alan
</span>
<span
class="icon-container"
>
<span
class="owner-icon-wrap"
data-placement="bottom"
data-toggle="tooltip"
title="Owner"
>
<svg
class="owner-icon"
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<polygon
points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"
/>
</svg>
</span>
</span>
</li>
<li>
<span
class="username"
style="color: rgb(156, 252, 223);"
>
dan
</span>
<span
class="icon-container"
/>
</li>
</ul>
</div>
</div>
</div>
<button
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
class="navbar-toggler"
data-target="#navbarSupportedContent"
data-toggle="collapse"
type="button"
>
<span
class="navbar-toggler-icon"
/>
</button>
<div
class="collapse navbar-collapse"
id="navbarSupportedContent"
>
<ul
class="navbar-nav ml-auto"
>
<li
class="nav-item"
>
<button
class="btn btn-plain nav-link"
target="blank"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="12"
cy="12"
r="10"
/>
<line
x1="12"
x2="12"
y1="8"
y2="16"
/>
<line
x1="8"
x2="16"
y1="12"
y2="12"
/>
</svg>
<span />
</button>
</li>
<li
class=" nav-item"
>
<button
class="btn btn-plain nav-link"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="12"
cy="12"
r="3"
/>
<path
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"
/>
</svg>
<span />
</button>
</li>
<li
class="nav-item"
>
<button
class="btn btn-plain nav-link"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="12"
cy="12"
r="10"
/>
<line
x1="12"
x2="12"
y1="16"
y2="12"
/>
<line
x1="12"
x2="12"
y1="8"
y2="8"
/>
</svg>
<span />
</button>
</li>
</ul>
</div>
</nav>
</DocumentFragment>
`;

View File

@ -1,63 +1,63 @@
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import shortId from 'shortid'
import { Info, Settings, PlusCircle, User, Users, Lock, Unlock, Star } from 'react-feather'
import logoImg from 'img/logo.png'
import Dropdown, { DropdownTrigger, DropdownContent } from 'react-simple-dropdown'
import Username from 'components/Username'
import Clipboard from 'clipboard'
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import shortId from 'shortid';
import { Info, Settings, PlusCircle, User, Users, Lock, Unlock, Star } from 'react-feather';
import logoImg from 'img/logo.png';
import Dropdown, { DropdownTrigger, DropdownContent } from 'react-simple-dropdown';
import Username from 'components/Username';
import Clipboard from 'clipboard';
import $ from 'jquery';
class Nav extends Component {
componentDidMount() {
const clip = new Clipboard('.clipboard-trigger')
const clip = new Clipboard('.clipboard-trigger');
clip.on('success', () => {
$('.room-id').tooltip('show')
$('.room-id').tooltip('show');
setTimeout(() => {
$('.room-id').tooltip('hide')
}, 3000)
})
$('.room-id').tooltip('hide');
}, 3000);
});
$(() => {
$('.room-id').tooltip({
trigger: 'manual',
})
});
$('.lock-room').tooltip({
trigger: 'manual',
})
})
});
});
}
componentDidUpdate() {
$(() => {
$('.me-icon-wrap').tooltip()
$('.owner-icon-wrap').tooltip()
})
$('.me-icon-wrap').tooltip();
$('.owner-icon-wrap').tooltip();
});
}
newRoom() {
$('.navbar-collapse').collapse('hide')
window.open(`/${shortId.generate()}`)
$('.navbar-collapse').collapse('hide');
window.open(`/${shortId.generate()}`);
}
handleSettingsClick() {
$('.navbar-collapse').collapse('hide')
this.props.openModal('Settings')
$('.navbar-collapse').collapse('hide');
this.props.openModal('Settings');
}
handleAboutClick() {
$('.navbar-collapse').collapse('hide')
this.props.openModal('About')
$('.navbar-collapse').collapse('hide');
this.props.openModal('About');
}
handleToggleLock() {
if (!this.props.iAmOwner) {
$('.lock-room').tooltip('show')
setTimeout(() => $('.lock-room').tooltip('hide'), 3000)
return
$('.lock-room').tooltip('show');
setTimeout(() => $('.lock-room').tooltip('hide'), 3000);
return;
}
this.props.toggleLockRoom()
this.props.toggleLockRoom();
}
render() {
@ -71,7 +71,8 @@ class Nav extends Component {
data-placement="bottom"
title={this.props.translations.copyButtonTooltip}
data-clipboard-text={`${window.location.origin}/${this.props.roomId}`}
className="btn btn-plain btn-link clipboard-trigger room-id ellipsis">
className="btn btn-plain btn-link clipboard-trigger room-id ellipsis"
>
{`/${this.props.roomId}`}
</button>
@ -83,18 +84,14 @@ class Nav extends Component {
data-placement="bottom"
title="You must be the owner to lock or unlock the room"
>
{this.props.roomLocked &&
<Lock />
}
{!this.props.roomLocked &&
<Unlock className="muted" />
}
{this.props.roomLocked && <Lock />}
{!this.props.roomLocked && <Unlock className="muted" />}
</button>
</span>
<Dropdown className="members-dropdown">
<DropdownTrigger>
<button className="btn btn-link btn-plain members-action">
<button className="btn btn-link btn-plain members-action" title="Users">
<Users className="users-icon" />
</button>
<span>{this.props.members.length}</span>
@ -105,16 +102,16 @@ class Nav extends Component {
<li key={`user-${index}`}>
<Username username={member.username} />
<span className="icon-container">
{member.id === this.props.userId &&
{member.id === this.props.userId && (
<span data-toggle="tooltip" data-placement="bottom" title="Me" className="me-icon-wrap">
<User className="me-icon" />
</span>
}
{member.isOwner &&
)}
{member.isOwner && (
<span data-toggle="tooltip" data-placement="bottom" title="Owner" className="owner-icon-wrap">
<Star className="owner-icon" />
</span>
}
)}
</span>
</li>
))}
@ -130,25 +127,34 @@ class Nav extends Component {
data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation">
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon" />
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<button className="btn btn-plain nav-link" onClick={this.newRoom.bind(this)}target="blank"><PlusCircle /> <span>{this.props.translations.newRoomButton}</span></button>
<button className="btn btn-plain nav-link" onClick={this.newRoom.bind(this)} target="blank">
<PlusCircle /> <span>{this.props.translations.newRoomButton}</span>
</button>
</li>
<li className="
nav-item">
<button onClick={this.handleSettingsClick.bind(this)} className="btn btn-plain nav-link"><Settings /> <span>{this.props.translations.settingsButton}</span></button>
<li
className="
nav-item"
>
<button onClick={this.handleSettingsClick.bind(this)} className="btn btn-plain nav-link">
<Settings /> <span>{this.props.translations.settingsButton}</span>
</button>
</li>
<li className="nav-item">
<button onClick={this.handleAboutClick.bind(this)} className="btn btn-plain nav-link"><Info /> <span>{this.props.translations.aboutButton}</span></button>
<button onClick={this.handleAboutClick.bind(this)} className="btn btn-plain nav-link">
<Info /> <span>{this.props.translations.aboutButton}</span>
</button>
</li>
</ul>
</div>
</nav>
)
);
}
}
@ -161,6 +167,6 @@ Nav.propTypes = {
openModal: PropTypes.func.isRequired,
iAmOwner: PropTypes.bool.isRequired,
translations: PropTypes.object.isRequired,
}
};
export default Nav
export default Nav;

View File

@ -1,14 +1,13 @@
import React from 'react'
import renderer from 'react-test-renderer'
import Notice from './index.js'
import { mount } from 'enzyme'
import React from 'react';
import { render } from '@testing-library/react';
import Notice from '.';
test.skip('Notice Component', () => {
const component = mount(
<Notice>
test('Notice component is displaying', async () => {
const { asFragment } = render(
<Notice level={'warning'}>
<div>Hello world</div>
</Notice>
)
);
expect(component).toMatchSnapshot()
})
expect(asFragment()).toMatchSnapshot();
});

View File

@ -1,15 +1,15 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Notice Component 1`] = `
<div
className={undefined}
>
exports[`Notice component is displaying 1`] = `
<DocumentFragment>
<div>
<div
className="info"
class="warning"
>
<div>
Hello world
</div>
</div>
</div>
</div>
</DocumentFragment>
`;

View File

@ -0,0 +1,68 @@
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import RoomLink from '.';
import mock$ from 'jquery';
const mockTooltip = jest.fn().mockImplementation(param => {
// console.log('tooltip', param);
});
jest.mock('jquery', () => {
return jest.fn().mockImplementation(param => {
// console.log('$', param);
if (typeof param === 'function') {
param();
}
return {
tooltip: mockTooltip,
};
});
});
jest.useFakeTimers();
const mockTranslations = {
copyButtonTooltip: 'copyButton',
};
describe('RoomLink', () => {
afterEach(() => {
mock$.mockClear();
});
it('should display', async () => {
const { asFragment, unmount } = render(<RoomLink roomId="roomId" translations={mockTranslations} />);
expect(asFragment()).toMatchSnapshot();
expect(mock$).toHaveBeenLastCalledWith('.copy-room');
expect(mockTooltip).toHaveBeenLastCalledWith({ trigger: 'manual' });
mock$.mockClear();
unmount();
expect(mock$).toHaveBeenLastCalledWith('.copy-room');
expect(mockTooltip).toHaveBeenLastCalledWith('hide');
});
it('should copy link', async () => {
// Mock execCommand for paste
document.execCommand = jest.fn(() => true);
const { getByTitle } = render(<RoomLink roomId="roomId" translations={mockTranslations} />);
fireEvent.click(getByTitle(mockTranslations.copyButtonTooltip));
expect(document.execCommand).toHaveBeenLastCalledWith('copy');
expect(mock$).toHaveBeenCalledTimes(4);
expect(mock$).toHaveBeenLastCalledWith('.copy-room');
expect(mockTooltip).toHaveBeenLastCalledWith('show');
// Wait for tooltip to close
jest.runAllTimers();
expect(mock$).toHaveBeenCalledTimes(6);
expect(mock$).toHaveBeenLastCalledWith('.copy-room');
expect(mockTooltip).toHaveBeenLastCalledWith('hide');
});
});

View File

@ -0,0 +1,59 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`RoomLink should display 1`] = `
<DocumentFragment>
<form>
<div
class="form-group"
>
<div
class="input-group"
>
<input
class="form-control"
id="room-url"
readonly=""
type="text"
value="http://localhost/roomId"
/>
<div
class="input-group-append"
>
<button
class="copy-room btn btn-secondary"
data-clipboard-text="http://localhost/roomId"
data-placement="bottom"
data-toggle="tooltip"
title="copyButton"
type="button"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<rect
height="13"
rx="2"
ry="2"
width="13"
x="9"
y="9"
/>
<path
d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"
/>
</svg>
</button>
</div>
</div>
</div>
</form>
</DocumentFragment>
`;

View File

@ -1,50 +1,56 @@
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Copy } from 'react-feather'
import Clipboard from 'clipboard'
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Copy } from 'react-feather';
import Clipboard from 'clipboard';
import $ from 'jquery';
class RoomLink extends Component {
constructor(props) {
super(props)
super(props);
this.state = {
roomUrl: `${window.location.origin}/${props.roomId}`,
}
};
}
componentDidMount() {
const clip = new Clipboard('.copy-room')
const clip = new Clipboard('.copy-room');
clip.on('success', () => {
$('.copy-room').tooltip('show')
$('.copy-room').tooltip('show');
setTimeout(() => {
$('.copy-room').tooltip('hide')
}, 3000)
})
$('.copy-room').tooltip('hide');
}, 3000);
});
$(() => {
$('.copy-room').tooltip({
trigger: 'manual',
})
})
});
});
}
componentWillUnmount() {
$('.copy-room').tooltip('hide')
if ($('.copy-room').tooltip) $('.copy-room').tooltip('hide');
}
render() {
return (
<form>
<div className="form-group">
<div className="input-group">
<input id="room-url" className="form-control" type="text" readOnly value={this.state.roomUrl} />
<div className="input-group-append">
<div className='form-group'>
<div className='input-group'>
<input
id='room-url'
className='form-control'
type='text'
readOnly
value={this.state.roomUrl}
/>
<div className='input-group-append'>
<button
className="copy-room btn btn-secondary"
type="button"
data-toggle="tooltip"
data-placement="bottom"
className='copy-room btn btn-secondary'
type='button'
data-toggle='tooltip'
data-placement='bottom'
data-clipboard-text={this.state.roomUrl}
title={this.props.translations.copyButtonTooltip}
>
@ -54,13 +60,13 @@ class RoomLink extends Component {
</div>
</div>
</form>
)
);
}
}
RoomLink.propTypes = {
roomId: PropTypes.string.isRequired,
translations: PropTypes.object.isRequired,
}
};
export default RoomLink
export default RoomLink;

View File

@ -0,0 +1,8 @@
import React from 'react';
import { render } from '@testing-library/react';
import RoomLocked from '.';
test('RoomLocked component should display', () => {
const { asFragment } = render(<RoomLocked modalContent={'test'} />);
expect(asFragment()).toMatchSnapshot();
});

View File

@ -0,0 +1,9 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`RoomLocked component should display 1`] = `
<DocumentFragment>
<div>
test
</div>
</DocumentFragment>
`;

View File

@ -0,0 +1,70 @@
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Settings from '.';
const mockTranslations = {
sound: 'soundCheck',
};
jest.mock('components/T', () => {
return jest.fn().mockImplementation(({ path }) => {
return mockTranslations[path] || 'default';
});
});
// To avoid missing provider
jest.mock('components/T');
jest.mock('components/RoomLink');
describe('Settings component', () => {
it('should display', async () => {
const { asFragment } = render(
<Settings
soundIsEnabled={true}
toggleSoundEnabled={() => {}}
roomId="roomId"
setLanguage={() => {}}
translations={mockTranslations}
/>,
);
expect(asFragment()).toMatchSnapshot();
});
it('should toggle sound', async () => {
const toggleSound = jest.fn();
const { getAllByText } = render(
<Settings
soundIsEnabled={true}
toggleSoundEnabled={toggleSound}
roomId="roomId"
setLanguage={() => {}}
translations={mockTranslations}
/>,
);
//console.log(getAllByText(mockTranslations.sound)[1]);
fireEvent.click(getAllByText(mockTranslations.sound)[1]);
expect(toggleSound).toHaveBeenCalledWith(false);
});
it('should change lang', async () => {
const changeLang = jest.fn();
const { getByDisplayValue } = render(
<Settings
soundIsEnabled={true}
toggleSoundEnabled={() => {}}
roomId="roomId"
setLanguage={changeLang}
translations={{}}
/>,
);
fireEvent.change(getByDisplayValue('English'), { target: { value: 'de' } });
expect(changeLang).toHaveBeenCalledWith('de');
});
});

View File

@ -0,0 +1,157 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Settings component should display 1`] = `
<DocumentFragment>
<div
class="styles"
>
<section>
<h4>
soundCheck
</h4>
<form>
<div
class="form-check"
>
<label
class="form-check-label"
for="sound-control"
>
<input
checked=""
class="form-check-input"
id="sound-control"
type="checkbox"
/>
soundCheck
</label>
</div>
</form>
</section>
<section>
<h4
class="mb-3"
>
default
</h4>
</section>
<section>
<h4
class="mb-3"
>
default
</h4>
<p>
<a
href="https://github.com/darkwire/darkwire.io/blob/master/client/README.md#translations"
rel="noopener noreferrer"
target="_blank"
>
default
</a>
</p>
<div
class="form-group"
>
<select
class="form-control"
>
<option
value="en"
>
English
</option>
<option
value="fr"
>
Français
</option>
<option
value="oc"
>
Occitan
</option>
<option
value="de"
>
Deutsch
</option>
<option
value="nl"
>
Nederlands
</option>
<option
value="it"
>
Italiano
</option>
<option
value="zhCN"
>
中文
</option>
</select>
</div>
</section>
<section>
<h4>
default
</h4>
<p>
default
</p>
</section>
<section>
<h4>
default
</h4>
<p>
default
</p>
</section>
<section>
<h4>
default
</h4>
<p>
default
</p>
<ul>
<li>
/nick [username]
<span
class="text-muted"
>
default
</span>
</li>
<li>
/me [action]
<span
class="text-muted"
>
default
</span>
</li>
<li>
/clear
<span
class="text-muted"
>
default
</span>
</li>
<li>
/help
<span
class="text-muted"
>
default
</span>
</li>
</ul>
</section>
</div>
</DocumentFragment>
`;

View File

@ -0,0 +1,32 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getTranslations } from 'i18n';
import _ from 'lodash';
const regex = /{(.*?)}/g;
class T extends Component {
render() {
const t = getTranslations(this.props.language);
const englishT = getTranslations('en');
const str =
_.get(t, this.props.path, '') || _.get(englishT, this.props.path, '');
let string = str.split(regex);
if (this.props.data) {
string = string.map((word) => {
if (this.props.data[word]) {
return this.props.data[word];
}
return word;
});
return <span>{string}</span>;
}
return string;
}
}
T.propTypes = {
path: PropTypes.string.isRequired,
};
export default T;

View File

@ -0,0 +1,33 @@
import React from 'react';
import { render } from '@testing-library/react';
import T from './T';
// To avoid missing provider
jest.mock('components/T');
test('T component is displaying', async () => {
const { asFragment, rerender } = render(<T path="welcomeHeader" language="en" />);
expect(asFragment()).toMatchSnapshot();
rerender(<T path="welcomeHeader" language="fr" />);
expect(asFragment()).toMatchSnapshot();
rerender(<T path="welcomeHeader" language="xx" />);
expect(asFragment()).toMatchSnapshot();
rerender(<T path="missingKey" language="en" />);
expect(asFragment()).toMatchSnapshot();
rerender(<T path="userJoined" language="en" data={{ username: 'Alan' }} />);
expect(asFragment()).toMatchSnapshot();
rerender(<T path="userJoined" language="en" />);
expect(asFragment()).toMatchSnapshot();
});

View File

@ -0,0 +1,35 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`T component is displaying 1`] = `
<DocumentFragment>
Welcome to Darkwire v2.0
</DocumentFragment>
`;
exports[`T component is displaying 2`] = `
<DocumentFragment>
Bienvenue sur Darkwire v2.0
</DocumentFragment>
`;
exports[`T component is displaying 3`] = `
<DocumentFragment>
Welcome to Darkwire v2.0
</DocumentFragment>
`;
exports[`T component is displaying 4`] = `<DocumentFragment />`;
exports[`T component is displaying 5`] = `
<DocumentFragment>
<span>
Alan joined
</span>
</DocumentFragment>
`;
exports[`T component is displaying 6`] = `
<DocumentFragment>
username joined
</DocumentFragment>
`;

View File

@ -1,36 +1,6 @@
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {getTranslations} from 'i18n';
import _ from 'lodash';
import { connect } from 'react-redux'
import { connect } from 'react-redux';
import T from 'components/T/T';
const regex = /{(.*?)}/g;
class T extends Component {
render() {
const t = getTranslations(this.props.language);
const englishT = getTranslations('en');
const str = _.get(t, this.props.path, '') || _.get(englishT, this.props.path, '')
let string = str.split(regex);
if (this.props.data) {
string = string.map(word => {
if (this.props.data[word]) {
return this.props.data[word];
}
return word;
});
return <span>{string}</span>
}
return string;
}
}
T.propTypes = {
path: PropTypes.string.isRequired,
}
export default connect(
(state, ownProps) => ({
export default connect((state, ownProps) => ({
language: state.app.language,
}),
)(T)
}))(T);

View File

@ -0,0 +1,10 @@
import React from 'react';
import { render } from '@testing-library/react';
import Username from '.';
test('Username component is displaying', async () => {
const { asFragment } = render(<Username username='paul' />);
expect(asFragment()).toMatchSnapshot();
});

View File

@ -0,0 +1,12 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Username component is displaying 1`] = `
<DocumentFragment>
<span
class="username"
style="color: rgb(157, 242, 249);"
>
paul
</span>
</DocumentFragment>
`;

View File

@ -0,0 +1,12 @@
import React from 'react';
import { render } from '@testing-library/react';
import Welcome from '.';
test('Welcome component is displaying', async () => {
const { asFragment } = render(
<Welcome roomId='roomtest' close={() => {}} translations={{}} />
);
expect(asFragment()).toMatchSnapshot();
});

View File

@ -0,0 +1,106 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Welcome component is displaying 1`] = `
<DocumentFragment>
<div>
<div>
v2.0 is a complete rewrite and includes several new features. Here are some highlights:
<ul
class="native"
>
<li>
Support on all modern browsers (Chrome, Firefox, Safari, Safari iOS, Android)
</li>
<li>
Slash commands (/nick, /me, /clear)
</li>
<li>
Room owners can lock the room, preventing anyone else from joining
</li>
<li>
Front-end rewritten in React.js and Redux
</li>
<li>
Send files up to 4 MB
</li>
</ul>
<div>
You can learn more
<a
href="https://github.com/darkwire/darkwire.io"
rel="noopener noreferrer"
target="_blank"
>
here
</a>
.
</div>
</div>
<br />
<p
class="mb-2"
>
Others can join this room using the following URL:
</p>
<form>
<div
class="form-group"
>
<div
class="input-group"
>
<input
class="form-control"
id="room-url"
readonly=""
type="text"
value="http://localhost/roomtest"
/>
<div
class="input-group-append"
>
<button
class="copy-room btn btn-secondary"
data-clipboard-text="http://localhost/roomtest"
data-placement="bottom"
data-toggle="tooltip"
type="button"
>
<svg
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<rect
height="13"
rx="2"
ry="2"
width="13"
x="9"
y="9"
/>
<path
d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"
/>
</svg>
</button>
</div>
</div>
</div>
</form>
<div
class="react-modal-footer"
>
<button
class="btn btn-primary btn-lg"
/>
</div>
</div>
</DocumentFragment>
`;

View File

@ -1 +1,2 @@
/* istanbul ignore file */
export default process.env.NODE_ENV

View File

@ -1,9 +1,10 @@
import { getTranslations } from './index.js'
import { getTranslations } from './index.js';
test('Get translation', () => {
expect(getTranslations('en').welcomeHeader).toBe("Welcome to Darkwire v2.0");
expect(getTranslations('fr').welcomeHeader).toBe("Bienvenue sur Darkwire v2.0");
expect(getTranslations('zh-CN').welcomeHeader).toBe("欢迎来到Darkwire v2.0");
expect(getTranslations('en-US').welcomeHeader).toBe("Welcome to Darkwire v2.0");
expect(getTranslations('ru-CH').welcomeHeader).toBe("Welcome to Darkwire v2.0");
})
expect(getTranslations('en').welcomeHeader).toBe('Welcome to Darkwire v2.0');
expect(getTranslations().welcomeHeader).toBe('Welcome to Darkwire v2.0');
expect(getTranslations('fr').welcomeHeader).toBe('Bienvenue sur Darkwire v2.0');
expect(getTranslations('zh-CN').welcomeHeader).toBe('欢迎来到Darkwire v2.0');
expect(getTranslations('en-US').welcomeHeader).toBe('Welcome to Darkwire v2.0');
expect(getTranslations('ru-CH').welcomeHeader).toBe('Welcome to Darkwire v2.0');
});

View File

@ -1,3 +1,4 @@
/* istanbul ignore file */
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

5
client/src/index.test.js Normal file
View File

@ -0,0 +1,5 @@
describe('Timezones', () => {
it('should always be UTC', () => {
expect(new Date().getTimezoneOffset()).toBe(0);
});
});

View File

@ -0,0 +1,183 @@
import reducer from './activities';
describe('Activities reducer', () => {
it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual({
items: [],
});
});
it('should handle CLEAR_ACTVITIES', () => {
expect(reducer({ items: [{}, {}] }, { type: 'CLEAR_ACTIVITIES' })).toEqual({
items: [],
});
});
it('should handle SEND_ENCRYPTED_MESSAGE_SLASH_COMMAND', () => {
expect(
reducer({ items: [] }, { type: 'SEND_ENCRYPTED_MESSAGE_SLASH_COMMAND', payload: { payload: 'content' } }),
).toEqual({ items: [{ payload: 'content', type: 'SLASH_COMMAND' }] });
});
it('should handle SEND_ENCRYPTED_MESSAGE_FILE_TRANSFER', () => {
expect(
reducer({ items: [] }, { type: 'SEND_ENCRYPTED_MESSAGE_FILE_TRANSFER', payload: { payload: 'content' } }),
).toEqual({ items: [{ payload: 'content', type: 'FILE' }] });
});
it('should handle SEND_ENCRYPTED_MESSAGE_TEXT_MESSAGE', () => {
expect(
reducer({ items: [] }, { type: 'SEND_ENCRYPTED_MESSAGE_TEXT_MESSAGE', payload: { payload: 'content' } }),
).toEqual({ items: [{ payload: 'content', type: 'TEXT_MESSAGE' }] });
});
it('should handle RECEIVE_ENCRYPTED_MESSAGE_TEXT_MESSAGE', () => {
expect(
reducer(
{ items: [] },
{ type: 'RECEIVE_ENCRYPTED_MESSAGE_TEXT_MESSAGE', payload: { payload: { payload: 'content' } } },
),
).toEqual({ items: [{ payload: 'content', type: 'TEXT_MESSAGE' }] });
});
it('should handle SEND_ENCRYPTED_MESSAGE_SEND_FILE', () => {
expect(
reducer({ items: [] }, { type: 'SEND_ENCRYPTED_MESSAGE_SEND_FILE', payload: { payload: 'content' } }),
).toEqual({ items: [{ payload: 'content', type: 'SEND_FILE' }] });
});
it('should handle RECEIVE_ENCRYPTED_MESSAGE_SEND_FILE', () => {
expect(
reducer(
{ items: [] },
{ type: 'RECEIVE_ENCRYPTED_MESSAGE_SEND_FILE', payload: { payload: { message: 'content' } } },
),
).toEqual({ items: [{ message: 'content', type: 'RECEIVE_FILE' }] });
});
it('should handle RECEIVE_ENCRYPTED_MESSAGE_ADD_USER', () => {
const payload1 = {
payload: { content: 'content', id: 'idalan', username: 'alan' },
state: {
room: {
members: [{ id: 'iddan' }],
},
},
};
expect(reducer({ items: [] }, { type: 'RECEIVE_ENCRYPTED_MESSAGE_ADD_USER', payload: payload1 })).toEqual({
items: [{ type: 'USER_ENTER', userId: 'idalan', username: 'alan' }],
});
// Test already reveived user
const payload2 = {
payload: { content: 'content', id: 'idalan', username: 'alan' },
state: {
room: {
members: [{ id: 'idalan' }],
},
},
};
expect(reducer({ items: [] }, { type: 'RECEIVE_ENCRYPTED_MESSAGE_ADD_USER', payload: payload2 })).toEqual({
items: [],
});
});
it('should handle USER_EXIT', () => {
expect(reducer({ items: [] }, { type: 'USER_EXIT', payload: { id: 'idalan', username: 'alan' } })).toEqual({
items: [{ type: 'USER_EXIT', userId: 'idalan', username: 'alan' }],
});
// Without id
expect(reducer({ items: [] }, { type: 'USER_EXIT', payload: { username: 'alan' } })).toEqual({
items: [],
});
});
it('should handle TOGGLE_LOCK_ROOM', () => {
expect(
reducer(
{ items: [] },
{ type: 'TOGGLE_LOCK_ROOM', payload: { id: 'idalan', username: 'alan', locked: true, sender: 'alan' } },
),
).toEqual({
items: [{ locked: true, sender: 'alan', type: 'TOGGLE_LOCK_ROOM', userId: 'idalan', username: 'alan' }],
});
});
it('should handle RECEIVE_TOGGLE_LOCK_ROOM', () => {
expect(
reducer(
{ items: [] },
{ type: 'RECEIVE_TOGGLE_LOCK_ROOM', payload: { id: 'idalan', username: 'alan', locked: true, sender: 'alan' } },
),
).toEqual({
items: [{ locked: true, sender: 'alan', type: 'TOGGLE_LOCK_ROOM', userId: 'idalan', username: 'alan' }],
});
});
it('should handle SHOW_NOTICE', () => {
expect(reducer({ items: [] }, { type: 'SHOW_NOTICE', payload: { message: 'Hello wordld!' } })).toEqual({
items: [{ message: 'Hello wordld!', type: 'NOTICE' }],
});
});
it('should handle SEND_ENCRYPTED_MESSAGE_CHANGE_USERNAME', () => {
const payload1 = { currentUsername: 'alan', newUsername: 'dan', sender: 'alan' };
expect(
reducer(
{
items: [
{ sender: 'alan', username: 'alan' },
{ sender: 'alice', username: 'alice' },
],
},
{ type: 'SEND_ENCRYPTED_MESSAGE_CHANGE_USERNAME', payload: payload1 },
),
).toEqual({
items: [
{ sender: 'alan', username: 'dan' },
{ sender: 'alice', username: 'alice' },
{ currentUsername: 'alan', newUsername: 'dan', type: 'CHANGE_USERNAME' },
],
});
});
it('should handle RECEIVE_ENCRYPTED_MESSAGE_CHANGE_USERNAME', () => {
const payload1 = { payload: { currentUsername: 'alan', newUsername: 'dan', sender: 'alan' } };
expect(
reducer(
{
items: [
{ sender: 'alan', username: 'alan', type: 'USER_ACTION' },
{ sender: 'alan', username: 'alan', type: 'TEXT_MESSAGE' },
{ sender: 'alan', username: 'alan', type: 'ANOTHER_TYPE' },
{ sender: 'alice', username: 'alice' },
],
},
{ type: 'RECEIVE_ENCRYPTED_MESSAGE_CHANGE_USERNAME', payload: payload1 },
),
).toEqual({
items: [
{ sender: 'alan', type: 'USER_ACTION', username: 'dan' },
{ sender: 'alan', type: 'TEXT_MESSAGE', username: 'dan' },
{ sender: 'alan', type: 'ANOTHER_TYPE', username: 'alan' },
{ sender: 'alice', username: 'alice' },
{ currentUsername: 'alan', newUsername: 'dan', type: 'CHANGE_USERNAME' },
],
});
});
it('should handle SEND_ENCRYPTED_MESSAGE_USER_ACTION', () => {
expect(
reducer({ items: [] }, { type: 'SEND_ENCRYPTED_MESSAGE_USER_ACTION', payload: { message: 'Hello wordld!' } }),
).toEqual({ items: [{ message: 'Hello wordld!', type: 'USER_ACTION' }] });
});
it('should handle RECEIVE_ENCRYPTED_MESSAGE_USER_ACTION', () => {
expect(
reducer(
{ items: [] },
{ type: 'RECEIVE_ENCRYPTED_MESSAGE_USER_ACTION', payload: { payload: { message: 'Hello wordld!' } } },
),
).toEqual({ items: [{ message: 'Hello wordld!', type: 'USER_ACTION' }] });
});
});

View File

@ -0,0 +1,72 @@
import reducer from './app';
import { getTranslations } from 'i18n';
jest.mock('i18n', () => {
return {
getTranslations: jest.fn().mockReturnValue({ path: 'test' }),
};
});
describe('App reducer', () => {
it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual({
language: 'en-US',
modalComponent: null,
scrolledToBottom: true,
socketConnected: false,
soundIsEnabled: true,
translations: { path: 'test' },
unreadMessageCount: 0,
windowIsFocused: true,
});
});
it('should handle OPEN_MODAL', () => {
expect(reducer({}, { type: 'OPEN_MODAL', payload: 'test' })).toEqual({ modalComponent: 'test' });
});
it('should handle CLOSE_MODAL', () => {
expect(reducer({}, { type: 'CLOSE_MODAL' })).toEqual({ modalComponent: null });
});
it('should handle SET_SCROLLED_TO_BOTTOM', () => {
expect(reducer({}, { type: 'SET_SCROLLED_TO_BOTTOM', payload: true })).toEqual({ scrolledToBottom: true });
expect(reducer({}, { type: 'SET_SCROLLED_TO_BOTTOM', payload: false })).toEqual({ scrolledToBottom: false });
});
it('should handle TOGGLE_WINDOW_FOCUS', () => {
expect(reducer({ unreadMessageCount: 10 }, { type: 'TOGGLE_WINDOW_FOCUS', payload: true })).toEqual({
windowIsFocused: true,
unreadMessageCount: 0,
});
});
it('should handle RECEIVE_ENCRYPTED_MESSAGE_TEXT_MESSAGE', () => {
expect(
reducer({ unreadMessageCount: 10, windowIsFocused: false }, { type: 'RECEIVE_ENCRYPTED_MESSAGE_TEXT_MESSAGE' }),
).toEqual({ unreadMessageCount: 11, windowIsFocused: false });
expect(
reducer({ unreadMessageCount: 10, windowIsFocused: true }, { type: 'RECEIVE_ENCRYPTED_MESSAGE_TEXT_MESSAGE' }),
).toEqual({ unreadMessageCount: 0, windowIsFocused: true });
});
it('should handle TOGGLE_SOUND_ENABLED', () => {
expect(reducer({}, { type: 'TOGGLE_SOUND_ENABLED', payload: true })).toEqual({
soundIsEnabled: true,
});
});
it('should handle TOGGLE_SOCKET_CONNECTED', () => {
expect(reducer({}, { type: 'TOGGLE_SOCKET_CONNECTED', payload: true })).toEqual({
socketConnected: true,
});
});
it('should handle CHANGE_LANGUAGE', () => {
getTranslations.mockReturnValueOnce({ path: 'new lang' });
expect(reducer({}, { type: 'CHANGE_LANGUAGE', payload: 'fr' })).toEqual({
language: 'fr',
translations: { path: 'new lang' },
});
});
});

View File

@ -1,3 +1,4 @@
/* istanbul ignore file */
import { combineReducers } from 'redux'
import app from './app'
import activities from './activities'

View File

@ -0,0 +1,154 @@
import reducer from './room';
describe('Room reducer', () => {
it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual({ id: '', isLocked: false, members: [] });
});
it('should handle USER_EXIT', () => {
const state = {
members: [
{ publicKey: { n: 'dankey' }, id: 'dankey', username: 'dan', isOwner: true },
{ publicKey: { n: 'alankey' }, id: 'alankey', username: 'alan', isOwner: false },
{ publicKey: { n: 'alicekey' }, id: 'alicekey', username: 'alice', isOwner: false },
],
};
const payload = {
members: [
{ publicKey: { n: 'alankey' }, isOwner: true },
{ publicKey: { n: 'alicekey' }, isOwner: false },
],
};
expect(reducer(state, { type: 'USER_EXIT', payload: payload })).toEqual({
members: [
{ id: 'alankey', isOwner: true, publicKey: { n: 'alankey' }, username: 'alan' },
{ id: 'alicekey', isOwner: false, publicKey: { n: 'alicekey' }, username: 'alice' },
],
});
});
it('should handle RECEIVE_ENCRYPTED_MESSAGE_ADD_USER', () => {
const state = {
members: [
{ publicKey: { n: 'alankey' }, id: 'alankey', username: 'alan', isOwner: true },
{ publicKey: { n: 'alicekey' }, id: 'alicekey', username: 'alice', isOwner: false },
{ publicKey: { n: 'dankey' }, id: 'dankey', username: 'dan', isOwner: false },
],
};
const payload = {
payload: {
username: 'dany',
isOwner: true,
publicKey: { n: 'dankey' },
},
};
expect(reducer(state, { type: 'RECEIVE_ENCRYPTED_MESSAGE_ADD_USER', payload: payload })).toEqual({
members: [
{ id: 'alankey', isOwner: true, publicKey: { n: 'alankey' }, username: 'alan' },
{ id: 'alicekey', isOwner: false, publicKey: { n: 'alicekey' }, username: 'alice' },
{ id: 'dankey', isOwner: true, publicKey: { n: 'dankey' }, username: 'dany' },
],
});
});
it('should handle CREATE_USER', () => {
const state = {
members: [
{ publicKey: { n: 'alankey' }, id: 'alankey', username: 'alan', isOwner: true },
{ publicKey: { n: 'alicekey' }, id: 'alicekey', username: 'alice', isOwner: false },
],
};
const payload = {
username: 'dan',
publicKey: { n: 'danKey' },
};
expect(reducer(state, { type: 'CREATE_USER', payload: payload })).toEqual({
members: [
{ id: 'alankey', isOwner: true, publicKey: { n: 'alankey' }, username: 'alan' },
{ id: 'alicekey', isOwner: false, publicKey: { n: 'alicekey' }, username: 'alice' },
{ id: 'danKey', publicKey: { n: 'danKey' }, username: 'dan' },
],
});
});
it('should handle USER_ENTER', () => {
const state = {
members: [
{ publicKey: { n: 'alankey' }, id: 'alankey', username: 'alan', isOwner: true },
{ publicKey: { n: 'alicekey' }, id: 'alicekey', username: 'alice', isOwner: false },
],
};
const payload = {
users: [
{ publicKey: { n: 'alankey' }, id: 'alankey', username: 'alan', isOwner: true },
{ publicKey: { n: 'alicekey' }, id: 'alicekey', username: 'alice', isOwner: false },
{ publicKey: { n: 'dankey' }, id: 'dankey', username: 'dan', isOwner: false },
],
isLocked: false,
id: 'test',
};
expect(reducer(state, { type: 'USER_ENTER', payload: payload })).toEqual({
id: 'test',
isLocked: false,
members: [
{ id: 'alankey', isOwner: true, publicKey: { n: 'alankey' }, username: 'alan' },
{ id: 'alicekey', isOwner: false, publicKey: { n: 'alicekey' }, username: 'alice' },
{ id: 'dankey', isOwner: false, publicKey: { n: 'dankey' } },
],
});
});
it('should handle TOGGLE_LOCK_ROOM', () => {
expect(reducer({ isLocked: true }, { type: 'TOGGLE_LOCK_ROOM' })).toEqual({ isLocked: false });
});
it('should handle RECEIVE_TOGGLE_LOCK_ROOM', () => {
expect(reducer({ isLocked: true }, { type: 'RECEIVE_TOGGLE_LOCK_ROOM', payload: { locked: false } })).toEqual({
isLocked: false,
});
});
it('should handle SEND_ENCRYPTED_MESSAGE_CHANGE_USERNAME', () => {
const state = {
members: [
{ publicKey: { n: 'alankey' }, id: 'alankey', username: 'alan', isOwner: true },
{ publicKey: { n: 'alicekey' }, id: 'alicekey', username: 'alice', isOwner: false },
{ publicKey: { n: 'dankey' }, id: 'dankey', username: 'dan', isOwner: false },
],
};
const payload = {
newUsername: 'alicette',
id: 'alicekey',
};
expect(reducer(state, { type: 'SEND_ENCRYPTED_MESSAGE_CHANGE_USERNAME', payload: payload })).toEqual({
members: [
{ id: 'alankey', isOwner: true, publicKey: { n: 'alankey' }, username: 'alan' },
{ id: 'alicekey', isOwner: false, publicKey: { n: 'alicekey' }, username: 'alicette' },
{ id: 'dankey', isOwner: false, publicKey: { n: 'dankey' }, username: 'dan' },
],
});
});
it('should handle RECEIVE_ENCRYPTED_MESSAGE_CHANGE_USERNAME', () => {
const state = {
members: [
{ publicKey: { n: 'alankey' }, id: 'alankey', username: 'alan', isOwner: true },
{ publicKey: { n: 'alicekey' }, id: 'alicekey', username: 'alice', isOwner: false },
{ publicKey: { n: 'dankey' }, id: 'dankey', username: 'dan', isOwner: false },
],
};
const payload = {
payload: {
newUsername: 'alicette',
id: 'alicekey',
},
};
expect(reducer(state, { type: 'RECEIVE_ENCRYPTED_MESSAGE_CHANGE_USERNAME', payload: payload })).toEqual({
members: [
{ id: 'alankey', isOwner: true, publicKey: { n: 'alankey' }, username: 'alan' },
{ id: 'alicekey', isOwner: false, publicKey: { n: 'alicekey' }, username: 'alicette' },
{ id: 'dankey', isOwner: false, publicKey: { n: 'dankey' }, username: 'dan' },
],
});
});
});

View File

@ -0,0 +1,29 @@
import reducer from './user';
jest.mock('i18n', () => {
return {
getTranslations: jest.fn().mockReturnValue({ path: 'test' }),
};
});
describe('User reducer', () => {
it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual({ id: '', privateKey: {}, publicKey: {}, username: '' });
});
it('should handle CREATE_USER', () => {
const payload = { publicKey: { n: 'alicekey' }, username: 'alice' };
expect(reducer({}, { type: 'CREATE_USER', payload })).toEqual({
id: 'alicekey',
publicKey: { n: 'alicekey' },
username: 'alice',
});
});
it('should handle SEND_ENCRYPTED_MESSAGE_CHANGE_USERNAME', () => {
const payload = { newUsername: 'alice' };
expect(reducer({ username: 'polux' }, { type: 'SEND_ENCRYPTED_MESSAGE_CHANGE_USERNAME', payload })).toEqual({
username: 'alice',
});
});
});

View File

@ -1,3 +1,4 @@
/* istanbul ignore file */
// This optional code is used to register a service worker.
// register() is not called by default.

View File

@ -1,4 +1,8 @@
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
// this adds jest-dom's custom assertions
import '@testing-library/jest-dom/extend-expect';
import { enableFetchMocks } from 'jest-fetch-mock';
configure({ adapter: new Adapter() });
enableFetchMocks();

View File

@ -1,3 +1,4 @@
/* istanbul ignore file */
import { createStore, applyMiddleware, compose } from 'redux'
import reducers from 'reducers'
import thunk from 'redux-thunk'

View File

@ -1,3 +1,5 @@
/* istanbul ignore file */
module.exports = {
plugins: [
require('autoprefixer')({}), // eslint-disable-line

View File

@ -1,4 +1,5 @@
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
/* istanbul ignore file */
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() })
Enzyme.configure({ adapter: new Adapter() });

File diff suppressed because it is too large Load Diff

View File

@ -19,9 +19,9 @@
"scripts": {
"build": "./build.sh",
"start": "cd server && CLIENT_DIST_DIRECTORY='../client/build' yarn start",
"setup": "cd client && yarn && cd ../server && yarn",
"setup": "yarn && cd client && yarn && cd ../server && yarn",
"dev": "concurrently 'cd client && yarn start' 'cd server && yarn dev'",
"test": "echo 'tests'"
"test": "concurrently 'cd client && yarn coverage' 'cd server && yarn test --watchAll=false'"
},
"devDependencies": {
"concurrently": "^4.1.0"