diff --git a/.codecov.yml b/.codecov.yml new file mode 100644 index 000000000..2767ed675 --- /dev/null +++ b/.codecov.yml @@ -0,0 +1,169 @@ +codecov: + #token: uuid # Your private repository token + #url: "http" # for Codecov Enterprise customers + #slug: "owner/repo" # for Codecov Enterprise customers + #branch: master # override the default branch + #bot: username # set user whom will be the consumer of oauth requests + #ci: # Custom CI domains if Codecov does not identify them automatically + # - ci.domain.com + # - !provider # ignore these providers when checking if CI passed + # # ex. You may test on Travis, Circle, and AppVeyor, but only need + # # to check if Travis passes. Therefore add: !circle and !appveyor + notify: + #after_n_builds: null # number of expected builds to recieve before sending notifications + # # after: check ci status unless disabled via require_ci_to_pass + require_ci_to_pass: yes # yes: will delay sending notifications until all ci is finished + # no: will send notifications without checking ci status and wait till "after_n_builds" are uploaded + #countdown: null # number of seconds to wait before first ci build check + #delay: null # number of seconds to wait between ci build checks + +coverage: + precision: 2 # 2 = xx.xx%, 0 = xx% + round: nearest # down|up|nearest - default down + # range: 50...60 # default 70...90. red...green + + #notify: + # irc: + # default: + # server: "chat.freenode.net"|encrypted + # branches: null # all branches by default + # threshold: 1% + # message: "Coverage {{changed}} for {{owner}}/{{repo}}" # customize the message + # flags: null + # paths: null + # + # slack: + # default: + # url: "http"|encrypted + # threshold: 1% + # branches: null # all branches by default + # message: "Coverage {{changed}} for {{owner}}/{{repo}}" # customize the message + # attachments: "sunburst, diff" + # only_pulls: false + # flags: null + # paths: null + # + # email: + # default: + # to: + # - example@domain.com + # - &author + # threshold: 1% + # only_pulls: false + # layout: header, diff, trends + # flags: null + # paths: null + # + # hipchat: + # default: + # url: "http"|encrypted + # room: name|id + # threshold: 1% + # token: encrypted + # branches: null # all branches by default + # notify: false # if the hipchat message is silent or loud (default false) + # message: "Coverage {{changed}} for {{owner}}/{{repo}}" # customize the message + # flags: null + # paths: null + # + # gitter: + # url: "http"|encrypted + # threshold: 1% + # branches: null # all branches by default + # message: "Coverage {{changed}} for {{owner}}/{{repo}}" # customize the message + # + # webhooks: + # _name_: + # url: "http"|encrypted + # threshold: 1% + # branches: null # all branches by default + + status: + project: + default: false # disable the default status that measures entire project + backend: # declare a new status context "backend" + against: parent + target: auto + threshold: null + #threshold: 1% + base: auto + if_no_uploads: error + if_not_found: success + if_ci_failed: error + only_pulls: false + #branches: + # - master + #flags: + # - integration + paths: + - backend/ # only include coverage in "backend/" folder + webapp: # declare a new status context "frontend" + against: parent + target: auto + threshold: null + #threshold: 1% + base: auto + if_no_uploads: error + if_not_found: success + if_ci_failed: error + only_pulls: false + #branches: + # - master + #flags: + # - integration + paths: + - webapp/ # only include coverage in "webapp/" folder + + patch: + default: false + # against: parent + # target: 80% + # branches: null + # if_no_uploads: success + # if_not_found: success + # if_ci_failed: error + # only_pulls: false + # flags: + # - integration + # paths: + # - folder + + #changes: + # default: + # against: parent + # branches: null + # if_no_uploads: error + # if_not_found: success + # if_ci_failed: error + # only_pulls: false + # flags: + # - integration + # paths: + # - folder + + #flags: + # integration: + # branches: + # - master + # ignore: + # - app/ui + + #ignore: # files and folders for processing + # - tests/* + + #fixes: + # - "old_path::new_path" + +comment: + # layout options are quite limited in v4.x - there have been way more options in v1.0 + layout: reach, diff, flags, files # mostly old options: header, diff, uncovered, reach, files, tree, changes, sunburst, flags + behavior: new # default = posts once then update, posts new if delete + # once = post once then updates + # new = delete old, post new + # spammy = post new + require_changes: false # if true: only post the comment if coverage changes + require_base: no # [yes :: must have a base report to post] + require_head: no # [yes :: must have a head report to post] + branches: null # branch names that can post comment + flags: null + paths: null \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 632786285..4d9a4c733 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,6 +10,8 @@ addons: before_install: - yarn global add wait-on + # Install Codecov + - yarn global add codecov - yarn install - cp cypress.env.template.json cypress.env.json @@ -18,6 +20,7 @@ install: - wait-on http://localhost:7474 && docker-compose exec neo4j migrate script: + # Backend - docker-compose exec backend yarn run lint - docker-compose exec backend yarn run test:jest --ci --verbose=false - docker-compose exec backend yarn run db:reset @@ -25,10 +28,14 @@ script: - docker-compose exec backend yarn run test:cucumber - docker-compose exec backend yarn run db:reset - docker-compose exec backend yarn run db:seed + # Frontend - docker-compose exec webapp yarn run lint - docker-compose exec webapp yarn run test --ci --verbose=false - docker-compose exec -d backend yarn run test:before:seeder + # Fullstack - CYPRESS_RETRIES=1 yarn run cypress:run + # Coverage + - codecov after_success: - wget https://raw.githubusercontent.com/DiscordHooks/travis-ci-discord-webhook/master/send.sh diff --git a/backend/package.json b/backend/package.json index b8202569f..f70c97737 100644 --- a/backend/package.json +++ b/backend/package.json @@ -15,7 +15,7 @@ "test:jest:cmd": "wait-on tcp:4001 tcp:4123 && jest --forceExit --detectOpenHandles --runInBand", "test:cucumber:cmd": "wait-on tcp:4001 tcp:4123 && cucumber-js --require-module @babel/register --exit test/", "test:jest:cmd:debug": "wait-on tcp:4001 tcp:4123 && node --inspect-brk ./node_modules/.bin/jest -i --forceExit --detectOpenHandles --runInBand", - "test:jest": "run-p --race test:before:* 'test:jest:cmd {@}' --", + "test:jest": "run-p --race test:before:* \"test:jest:cmd {@}\" --", "test:cucumber": " cross-env CLIENT_URI=http://localhost:4123 run-p --race test:before:* 'test:cucumber:cmd {@}' --", "test:jest:debug": "run-p --race test:before:* 'test:jest:cmd:debug {@}' --", "db:script:seed": "wait-on tcp:4001 && babel-node src/seed/seed-db.js", @@ -27,7 +27,17 @@ "jest": { "verbose": true, "collectCoverage": true, - "coverageReporters": ["text", "lcov"], + "collectCoverageFrom": [ + "**/*.js", + "!**/node_modules/**", + "!**/test/**", + "!**/dist/**", + "!**/src/**/?(*.)+(spec|test).js?(x)" + ], + "coverageReporters": [ + "text", + "lcov" + ], "testMatch": [ "**/src/**/?(*.)+(spec|test).js?(x)" ] @@ -96,4 +106,4 @@ "nodemon": "~1.19.0", "supertest": "~4.0.2" } -} +} \ No newline at end of file diff --git a/backend/src/middleware/permissionsMiddleware.js b/backend/src/middleware/permissionsMiddleware.js index 3688aec16..85c584407 100644 --- a/backend/src/middleware/permissionsMiddleware.js +++ b/backend/src/middleware/permissionsMiddleware.js @@ -75,6 +75,7 @@ const permissions = shield({ DeleteBadge: isAdmin, AddUserBadges: isAdmin, CreateSocialMedia: isAuthenticated, + DeleteSocialMedia: isAuthenticated, // AddBadgeRewarded: isAdmin, // RemoveBadgeRewarded: isAdmin, reward: isAdmin, diff --git a/backend/src/middleware/permissionsMiddleware.spec.js b/backend/src/middleware/permissionsMiddleware.spec.js index 89904a7bf..e3c4beb00 100644 --- a/backend/src/middleware/permissionsMiddleware.spec.js +++ b/backend/src/middleware/permissionsMiddleware.spec.js @@ -40,10 +40,13 @@ describe('authorization', () => { }) it('does not expose the owner\'s email address', async () => { + let response = {} try { await action() } catch (error) { - expect(error.response.data).toEqual({ User: [ { email: null } ] }) + response = error.response.data + } finally { + expect(response).toEqual({ User: [ null ] }) } }) }) @@ -74,11 +77,13 @@ describe('authorization', () => { }) it('does not expose the owner\'s email address', async () => { + let response try { await action() } catch (error) { - expect(error.response.data).toEqual({ User: [ { email: null } ] }) + response = error.response.data } + expect(response).toEqual({ User: [ null ] }) }) }) }) diff --git a/backend/src/middleware/slugify/uniqueSlug.js b/backend/src/middleware/slugify/uniqueSlug.js index 8b04edc6f..64e38c8ae 100644 --- a/backend/src/middleware/slugify/uniqueSlug.js +++ b/backend/src/middleware/slugify/uniqueSlug.js @@ -1,6 +1,6 @@ import slugify from 'slug' export default async function uniqueSlug (string, isUnique) { - let slug = slugify(string, { + let slug = slugify(string || 'anonymous', { lower: true }) if (await isUnique(slug)) return slug diff --git a/backend/src/middleware/slugify/uniqueSlug.spec.js b/backend/src/middleware/slugify/uniqueSlug.spec.js index 190899795..6772a20c2 100644 --- a/backend/src/middleware/slugify/uniqueSlug.spec.js +++ b/backend/src/middleware/slugify/uniqueSlug.spec.js @@ -15,4 +15,11 @@ describe('uniqueSlug', () => { .mockResolvedValueOnce(true) expect(uniqueSlug(string, isUnique)).resolves.toEqual('hello-world-1') }) + + it('slugify null string', () => { + const string = null + const isUnique = jest.fn() + .mockResolvedValue(true) + expect(uniqueSlug(string, isUnique)).resolves.toEqual('anonymous') + }) }) diff --git a/backend/src/middleware/slugifyMiddleware.spec.js b/backend/src/middleware/slugifyMiddleware.spec.js index bd524e0e4..6e667056c 100644 --- a/backend/src/middleware/slugifyMiddleware.spec.js +++ b/backend/src/middleware/slugifyMiddleware.spec.js @@ -77,7 +77,7 @@ describe('slugify', () => { describe('CreateUser', () => { const action = async (mutation, params) => { return authenticatedClient.request(`mutation { - ${mutation}(password: "yo", ${params}) { slug } + ${mutation}(password: "yo", email: "123@123.de", ${params}) { slug } }`) } it('generates a slug based on name', async () => { diff --git a/backend/src/middleware/userMiddleware.js b/backend/src/middleware/userMiddleware.js index 2979fdadf..4789b4cbd 100644 --- a/backend/src/middleware/userMiddleware.js +++ b/backend/src/middleware/userMiddleware.js @@ -1,5 +1,7 @@ -import createOrUpdateLocations from './nodes/locations' import dotenv from 'dotenv' +import { UserInputError } from 'apollo-server' + +import createOrUpdateLocations from './nodes/locations' dotenv.config() @@ -11,6 +13,10 @@ export default { return result }, UpdateUser: async (resolve, root, args, context, info) => { + const USERNAME_MIN_LENGTH = 3 // TODO move to the correct place + if (!args.name || args.name.length < USERNAME_MIN_LENGTH) { + throw new UserInputError(`Username must be at least ${USERNAME_MIN_LENGTH} characters long!`) + } const result = await resolve(root, args, context, info) await createOrUpdateLocations(args.id, args.locationName, context.driver) return result diff --git a/backend/src/middleware/userMiddleware.spec.js b/backend/src/middleware/userMiddleware.spec.js new file mode 100644 index 000000000..9aa8f96c1 --- /dev/null +++ b/backend/src/middleware/userMiddleware.spec.js @@ -0,0 +1,81 @@ +import { GraphQLClient } from 'graphql-request' +import { host } from '../jest/helpers' +import Factory from '../seed/factories' + +const factory = Factory() +let client + +afterAll(async () => { + await factory.cleanDatabase() +}) + +describe('userMiddleware', () => { + describe('create User', () => { + const mutation = ` + mutation($id: ID, $password: String!, $email: String!) { + CreateUser(id: $id, password: $password, email: $email) { + id + } + } + ` + client = new GraphQLClient(host) + + it('with password and email', async () => { + const variables = { + password: '123', + email: '123@123.de' + } + const expected = { + CreateUser: { + id: expect.any(String) + } + } + await expect(client.request(mutation, variables)) + .resolves.toEqual(expected) + }) + }) + + describe('update User', () => { + const mutation = ` + mutation($id: ID!, $name: String) { + UpdateUser(id: $id, name: $name) { + name + } + } + ` + client = new GraphQLClient(host) + + // TODO why is this failing - it returns { UpdateUser: null } - that should not be + /* it('name within specifications', async () => { + const variables = { + id: 'u1', + name: 'Peter Lustig' + } + const expected = { + UpdateUser: { + name: 'Peter Lustig' + } + } + await expect(client.request(mutation, variables)) + .resolves.toEqual(expected) + }) */ + + it('with no name', async () => { + const variables = { + id: 'u1' + } + const expected = 'Username must be at least 3 characters long!' + await expect(client.request(mutation, variables)) + .rejects.toThrow(expected) + }) + + it('with too short name', async () => { + const variables = { + id: 'u1' + } + const expected = 'Username must be at least 3 characters long!' + await expect(client.request(mutation, variables)) + .rejects.toThrow(expected) + }) + }) +}) diff --git a/backend/src/resolvers/socialMedia.js b/backend/src/resolvers/socialMedia.js index 310375820..ef143a478 100644 --- a/backend/src/resolvers/socialMedia.js +++ b/backend/src/resolvers/socialMedia.js @@ -3,6 +3,9 @@ import { neo4jgraphql } from 'neo4j-graphql-js' export default { Mutation: { CreateSocialMedia: async (object, params, context, resolveInfo) => { + /** + * TODO?: Creates double Nodes! + */ const socialMedia = await neo4jgraphql(object, params, context, resolveInfo, false) const session = context.driver.session() await session.run( @@ -15,6 +18,11 @@ export default { ) session.close() + return socialMedia + }, + DeleteSocialMedia: async (object, params, context, resolveInfo) => { + const socialMedia = await neo4jgraphql(object, params, context, resolveInfo, false) + return socialMedia } } diff --git a/backend/src/resolvers/socialMedia.spec.js b/backend/src/resolvers/socialMedia.spec.js index b97316543..9d1d76726 100644 --- a/backend/src/resolvers/socialMedia.spec.js +++ b/backend/src/resolvers/socialMedia.spec.js @@ -7,9 +7,18 @@ const factory = Factory() describe('CreateSocialMedia', () => { let client let headers - const mutation = ` + const mutationC = ` mutation($url: String!) { CreateSocialMedia(url: $url) { + id + url + } + } + ` + const mutationD = ` + mutation($id: ID!) { + DeleteSocialMedia(id: $id) { + id url } } @@ -30,20 +39,63 @@ describe('CreateSocialMedia', () => { await factory.cleanDatabase() }) + describe('unauthenticated', () => { + it('throws authorization error', async () => { + client = new GraphQLClient(host) + const variables = { url: 'http://nsosp.org' } + await expect( + client.request(mutationC, variables) + ).rejects.toThrow('Not Authorised') + }) + }) + describe('authenticated', () => { beforeEach(async () => { headers = await login({ email: 'test@example.org', password: '1234' }) client = new GraphQLClient(host, { headers }) }) + it('creates social media with correct URL', async () => { + const variables = { url: 'http://nsosp.org' } + await expect( + client.request(mutationC, variables) + ).resolves.toEqual(expect.objectContaining({ + CreateSocialMedia: { + id: expect.any(String), + url: 'http://nsosp.org' + } + })) + }) + + it('deletes social media', async () => { + const creationVariables = { url: 'http://nsosp.org' } + const { CreateSocialMedia } = await client.request(mutationC, creationVariables) + const { id } = CreateSocialMedia + + const deletionVariables = { id } + const expected = { + DeleteSocialMedia: { + id: id, + url: 'http://nsosp.org' + } + } + await expect( + client.request(mutationD, deletionVariables) + ).resolves.toEqual(expected) + }) + it('rejects empty string', async () => { const variables = { url: '' } - await expect(client.request(mutation, variables)).rejects.toThrow('Input is not a URL') + await expect( + client.request(mutationC, variables) + ).rejects.toThrow('Input is not a URL') }) it('validates URLs', async () => { const variables = { url: 'not-a-url' } - await expect(client.request(mutation, variables)).rejects.toThrow('Input is not a URL') + await expect( + client.request(mutationC, variables) + ).rejects.toThrow('Input is not a URL') }) }) }) diff --git a/backend/src/resolvers/user_management.spec.js b/backend/src/resolvers/user_management.spec.js index 94ec04203..7c0be08f3 100644 --- a/backend/src/resolvers/user_management.spec.js +++ b/backend/src/resolvers/user_management.spec.js @@ -339,7 +339,7 @@ describe('do not expose private RSA key', () => { email: 'apfel-strudel@test.org' } await client.request(gql` - mutation($id: ID, $password: String!, $slug: String, $name: String, $email: String) { + mutation($id: ID, $password: String!, $slug: String, $name: String, $email: String!) { CreateUser(id: $id, password: $password, slug: $slug, name: $name, email: $email) { id } diff --git a/backend/src/schema.graphql b/backend/src/schema.graphql index 4638fbd0d..902a7abf9 100644 --- a/backend/src/schema.graphql +++ b/backend/src/schema.graphql @@ -95,7 +95,7 @@ type User { id: ID! actorId: String name: String - email: String + email: String! slug: String password: String! avatar: String diff --git a/backend/src/seed/factories/users.js b/backend/src/seed/factories/users.js index 1bca0e243..a088b4c54 100644 --- a/backend/src/seed/factories/users.js +++ b/backend/src/seed/factories/users.js @@ -20,7 +20,7 @@ export default function create (params) { $name: String $slug: String $password: String! - $email: String + $email: String! $avatar: String $about: String $role: UserGroupEnum diff --git a/cypress/integration/common/settings.js b/cypress/integration/common/settings.js index e1f3cc5a8..b6621ec87 100644 --- a/cypress/integration/common/settings.js +++ b/cypress/integration/common/settings.js @@ -77,7 +77,7 @@ Then('I should be on the {string} page', page => { .should('contain', 'Social media') }) -Then('I add a social media link', () => { +When('I add a social media link', () => { cy.get("input[name='social-media']") .type('https://freeradical.zone/peter-pan') .get('button') @@ -87,7 +87,7 @@ Then('I add a social media link', () => { Then('it gets saved successfully', () => { cy.get('.iziToast-message') - .should('contain', 'Updated user') + .should('contain', 'Added social media') }) Then('the new social media link shows up on the page', () => { @@ -110,3 +110,13 @@ Then('they should be able to see my social media links', () => { .get('a[href="https://freeradical.zone/peter-pan"]') .should('have.length', 1) }) + +When('I delete a social media link', () => { + cy.get("a[name='delete']") + .click() +}) + +Then('it gets deleted successfully', () => { + cy.get('.iziToast-message') + .should('contain', 'Deleted social media') +}) diff --git a/cypress/integration/user_profile/SocialMedia.feature b/cypress/integration/user_profile/SocialMedia.feature index 988923c17..d21167c6b 100644 --- a/cypress/integration/user_profile/SocialMedia.feature +++ b/cypress/integration/user_profile/SocialMedia.feature @@ -19,3 +19,11 @@ Feature: List Social Media Accounts Given I have added a social media link When people visit my profile page Then they should be able to see my social media links + + Scenario: Deleting Social Media + Given I am on the "settings" page + And I click on the "Social media" link + Then I should be on the "/settings/my-social-media" page + Given I have added a social media link + When I delete a social media link + Then it gets deleted successfully diff --git a/docker-compose.travis.yml b/docker-compose.travis.yml index 8af3226e7..bc627a67a 100644 --- a/docker-compose.travis.yml +++ b/docker-compose.travis.yml @@ -11,6 +11,9 @@ services: build: context: webapp target: build-and-test + volumes: + #/nitro-web + - ./webapp/coverage:/nitro-web/coverage environment: - GRAPHQL_URI=http://backend:4000 backend: @@ -18,6 +21,8 @@ services: build: context: backend target: builder + volumes: + - ./backend/coverage:/nitro-backend/coverage ports: - 4001:4001 - 4123:4123 diff --git a/webapp/.babelrc b/webapp/.babelrc index fbd5b7451..b23873e12 100644 --- a/webapp/.babelrc +++ b/webapp/.babelrc @@ -1,4 +1,7 @@ { + "plugins": [ + "@babel/plugin-syntax-dynamic-import" + ], "presets": [ [ "@babel/preset-env", @@ -21,4 +24,4 @@ ] } } -} +} \ No newline at end of file diff --git a/webapp/components/User/index.spec.js b/webapp/components/User/index.spec.js index 9f45ae83a..4bc286d20 100644 --- a/webapp/components/User/index.spec.js +++ b/webapp/components/User/index.spec.js @@ -51,8 +51,8 @@ describe('User', () => { it('renders anonymous user', () => { const wrapper = Wrapper() - expect(wrapper.text()).not.toMatch('Tilda Swinton') - expect(wrapper.text()).toMatch('Anonymus') + expect(wrapper.text()).toBe('') + expect(mocks.$t).toHaveBeenCalledWith('profile.userAnonym') }) describe('given an user', () => { @@ -65,7 +65,7 @@ describe('User', () => { it('renders user name', () => { const wrapper = Wrapper() - expect(wrapper.text()).not.toMatch('Anonymous') + expect(mocks.$t).not.toHaveBeenCalledWith('profile.userAnonym') expect(wrapper.text()).toMatch('Tilda Swinton') }) @@ -77,7 +77,7 @@ describe('User', () => { it('renders anonymous user', () => { const wrapper = Wrapper() expect(wrapper.text()).not.toMatch('Tilda Swinton') - expect(wrapper.text()).toMatch('Anonymus') + expect(mocks.$t).toHaveBeenCalledWith('profile.userAnonym') }) describe('current user is a moderator', () => { diff --git a/webapp/components/User/index.vue b/webapp/components/User/index.vue index 6b0731981..857f4f302 100644 --- a/webapp/components/User/index.vue +++ b/webapp/components/User/index.vue @@ -12,7 +12,7 @@ Anonymus + >{{ $t('profile.userAnonym') }} @@ -47,7 +47,7 @@ {{ user.name | truncate(trunc, 18) }} + >{{ userName | truncate(18) }}
- {{ $t('login.hello') }} {{ user.name }} + {{ $t('login.hello') }} + {{ userName }} @@ -146,6 +149,10 @@ export default { quickSearchResults: 'search/quickResults', quickSearchPending: 'search/quickPending' }), + userName() { + const { name } = this.user || {} + return name || this.$t('profile.userAnonym') + }, routes() { if (!this.user.slug) { return [] diff --git a/webapp/locales/de.json b/webapp/locales/de.json index 14e709866..f4ea82e37 100644 --- a/webapp/locales/de.json +++ b/webapp/locales/de.json @@ -21,6 +21,7 @@ "following": "Folgt", "shouted": "Empfohlen", "commented": "Kommentiert", + "userAnonym": "Anonymus", "socialMedia": "Wo sonst finde ich" }, "notifications": { @@ -38,8 +39,10 @@ "data": { "name": "Deine Daten", "labelName": "Dein Name", + "namePlaceholder": "Petra Lustig", "labelCity": "Deine Stadt oder Region", - "labelBio": "Über dich" + "labelBio": "Über dich", + "success": "Deine Daten wurden erfolgreich aktualisiert!" }, "security": { "name": "Sicherheit", @@ -65,8 +68,10 @@ }, "social-media": { "name": "Soziale Medien", + "placeholder": "Füge eine Social-Media URL hinzu", "submit": "Link hinzufügen", - "success": "Profil aktualisiert" + "successAdd": "Social-Media hinzugefügt. Profil aktualisiert!", + "successDelete": "Social-Media gelöscht. Profil aktualisiert!" } }, "admin": { @@ -222,4 +227,4 @@ "shoutButton": { "shouted": "empfohlen" } -} +} \ No newline at end of file diff --git a/webapp/locales/en.json b/webapp/locales/en.json index 2ab796f4a..0dc953666 100644 --- a/webapp/locales/en.json +++ b/webapp/locales/en.json @@ -21,6 +21,7 @@ "following": "Following", "shouted": "Shouted", "commented": "Commented", + "userAnonym": "Anonymous", "socialMedia": "Where else can I find" }, "notifications": { @@ -38,8 +39,10 @@ "data": { "name": "Your data", "labelName": "Your Name", + "namePlaceholder": "Femanon Funny", "labelCity": "Your City or Region", - "labelBio": "About You" + "labelBio": "About You", + "success": "Your data was successfully updated!" }, "security": { "name": "Security", @@ -65,8 +68,10 @@ }, "social-media": { "name": "Social media", + "placeholder": "Add social media url", "submit": "Add link", - "success": "Updated user profile" + "successAdd": "Added social media. Updated user profile!", + "successDelete": "Deleted social media. Updated user profile!" } }, "admin": { @@ -222,4 +227,4 @@ "shoutButton": { "shouted": "shouted" } -} +} \ No newline at end of file diff --git a/webapp/locales/it.json b/webapp/locales/it.json index 0225babad..25005a07a 100644 --- a/webapp/locales/it.json +++ b/webapp/locales/it.json @@ -15,13 +15,15 @@ "followers": "Seguenti", "following": "Seguendo", "shouted": "Gridato", - "commented": "Commentato" + "commented": "Commentato", + "userAnonym": "Anonymous" }, "settings": { "name": "Impostazioni", "data": { "name": "I tuoi dati", "labelName": "Nome", + "namePlaceholder": "Anonymous", "labelCity": "La tua città o regione", "labelBio": "Su di te" }, diff --git a/webapp/locales/pl.json b/webapp/locales/pl.json index 0f2147996..506a04f1b 100644 --- a/webapp/locales/pl.json +++ b/webapp/locales/pl.json @@ -15,13 +15,15 @@ "followers": "Obserwujący", "following": "Obserwowani", "shouted": "Krzyknij", - "commented": "Skomentuj" + "commented": "Skomentuj", + "userAnonym": "Anonymous" }, "settings": { "name": "Ustawienia", "data": { "name": "Twoje dane", "labelName": "Twoje dane", + "namePlaceholder": "Anonymous", "labelCity": "Twoje miasto lub region", "labelBio": "O Tobie" }, diff --git a/webapp/locales/pt.json b/webapp/locales/pt.json index 4151f49c7..0636ba6f9 100644 --- a/webapp/locales/pt.json +++ b/webapp/locales/pt.json @@ -15,13 +15,15 @@ "followers": "Seguidores", "following": "Seguindo", "shouted": "Aclamou", - "commented": "Comentou" + "commented": "Comentou", + "userAnonym": "Anonymous" }, "settings": { "name": "Configurações", "data": { "name": "Seus dados", "labelName": "Seu nome", + "namePlaceholder": "Anonymous", "labelCity": "Sua cidade ou estado", "labelBio": "Sobre você" }, diff --git a/webapp/package.json b/webapp/package.json index e70d2b038..d96385c53 100644 --- a/webapp/package.json +++ b/webapp/package.json @@ -18,20 +18,32 @@ "jest": { "verbose": true, "collectCoverage": true, - "coverageReporters": ["text", "lcov"], - "moduleFileExtensions": [ - "js", - "json", - "vue" + "collectCoverageFrom": [ + "**/*.{js,vue}", + "!**/node_modules/**", + "!**/.nuxt/**", + "!**/?(*.)+(spec|test).js?(x)" + ], + "coverageReporters": [ + "text", + "lcov" ], "transform": { ".*\\.(vue)$": "vue-jest", "^.+\\.js$": "/node_modules/babel-jest" }, + "moduleFileExtensions": [ + "js", + "json", + "vue" + ], "moduleNameMapper": { "^@/(.*)$": "/src/$1", "^~/(.*)$": "/$1" - } + }, + "testMatch": [ + "**/?(*.)+(spec|test).js?(x)" + ] }, "dependencies": { "@human-connection/styleguide": "0.5.15", @@ -63,6 +75,7 @@ }, "devDependencies": { "@babel/core": "~7.4.4", + "@babel/plugin-syntax-dynamic-import": "^7.2.0", "@babel/preset-env": "~7.4.4", "@vue/cli-shared-utils": "~3.7.0", "@vue/eslint-config-prettier": "~4.0.1", @@ -86,4 +99,4 @@ "vue-jest": "~3.0.4", "vue-svg-loader": "~0.12.0" } -} +} \ No newline at end of file diff --git a/webapp/pages/profile/_id/_slug.vue b/webapp/pages/profile/_id/_slug.vue index d577b79c8..ecb0baa9d 100644 --- a/webapp/pages/profile/_id/_slug.vue +++ b/webapp/pages/profile/_id/_slug.vue @@ -16,7 +16,7 @@ > @@ -35,7 +35,7 @@ align="center" no-margin > - {{ user.name }} + {{ userName }} - Wem folgt {{ user.name | truncate(15) }}? + Wem folgt {{ userName | truncate(15) }}? @@ -168,7 +168,7 @@ tag="h5" color="soft" > - Wer folgt {{ user.name | truncate(15) }}? + Wer folgt {{ userName | truncate(15) }}? - - + - + {{ link.username }} @@ -393,6 +389,10 @@ export default { const username = url.split('/').pop() return { url, username, favicon } }) + }, + userName() { + const { name } = this.user || {} + return name || this.$t('profile.userAnonym') } }, watch: { diff --git a/webapp/pages/settings/index.spec.js b/webapp/pages/settings/index.spec.js new file mode 100644 index 000000000..8ee68172e --- /dev/null +++ b/webapp/pages/settings/index.spec.js @@ -0,0 +1,73 @@ +import { mount, createLocalVue } from '@vue/test-utils' +import index from './index.vue' +import Vue from 'vue' +import Vuex from 'vuex' +import Styleguide from '@human-connection/styleguide' + +const localVue = createLocalVue() + +localVue.use(Vuex) +localVue.use(Styleguide) + +describe('index.vue', () => { + let Wrapper + let store + let mocks + let getters + + beforeEach(() => { + mocks = { + $t: jest.fn(), + $apollo: { + mutate: jest + .fn() + .mockRejectedValue({ message: 'Ouch!' }) + .mockResolvedValueOnce({ + data: { + UpdateUser: { + id: 'u1', + name: 'Peter', + locationName: 'Berlin', + about: 'Smth' + } + } + }) + }, + $toast: { + error: jest.fn(), + success: jest.fn() + } + } + getters = { + 'auth/user': () => { + return {} + } + } + }) + + describe('mount', () => { + const Wrapper = () => { + store = new Vuex.Store({ + getters + }) + return mount(index, { store, mocks, localVue }) + } + + it('renders', () => { + expect(Wrapper().contains('div')).toBe(true) + }) + + describe('given a new username and hitting submit', () => { + it('calls updateUser mutation', () => { + const wrapper = Wrapper() + const input = wrapper.find('#name') + const submitForm = wrapper.find('.ds-form') + + input.setValue('Peter') + submitForm.trigger('submit') + + expect(mocks.$apollo.mutate).toHaveBeenCalled() + }) + }) + }) +}) diff --git a/webapp/pages/settings/index.vue b/webapp/pages/settings/index.vue index 5ff7c171e..a3b2298c3 100644 --- a/webapp/pages/settings/index.vue +++ b/webapp/pages/settings/index.vue @@ -9,7 +9,7 @@ model="name" icon="user" :label="$t('settings.data.labelName')" - :placeholder="$t('settings.data.labelName')" + :placeholder="$t('settings.data.namePlaceholder')" /> @@ -36,7 +36,7 @@ style="float: right;" icon="check" type="submit" - :loading="sending" + :loading="loadingData" primary > {{ $t('actions.save') }} @@ -88,8 +88,8 @@ export default { return { axiosSource: null, cities: [], - sending: false, - loading: false, + loadingData: false, + loadingGeo: false, formData: {} } }, @@ -111,13 +111,13 @@ export default { ...mapMutations({ setCurrentUser: 'auth/SET_USER' }), - submit() { - this.sending = true + async submit() { + this.loadingData = true const { name, about } = this.formData let { locationName } = this.formData locationName = locationName && (locationName['label'] || locationName) - this.$apollo - .mutate({ + try { + const { data } = await this.$apollo.mutate({ mutation, variables: { id: this.currentUser.id, @@ -135,15 +135,12 @@ export default { }) } }) - .then(data => { - this.$toast.success('Updated user') - }) - .catch(err => { - this.$toast.error(err.message) - }) - .finally(() => { - this.sending = false - }) + this.$toast.success(this.$t('settings.data.success')) + } catch (err) { + this.$toast.error(err.message) + } finally { + this.loadingData = false + } }, handleCityInput(value) { clearTimeout(timeout) @@ -181,7 +178,7 @@ export default { return } - this.loading = true + this.loadingGeo = true this.axiosSource = CancelToken.source() const place = encodeURIComponent(value) @@ -198,7 +195,7 @@ export default { this.cities = this.processCityResults(res) }) .finally(() => { - this.loading = false + this.loadingGeo = false }) } } diff --git a/webapp/pages/settings/my-social-media.spec.js b/webapp/pages/settings/my-social-media.spec.js index 4f48a2835..559ba87d2 100644 --- a/webapp/pages/settings/my-social-media.spec.js +++ b/webapp/pages/settings/my-social-media.spec.js @@ -71,6 +71,40 @@ describe('my-social-media.vue', () => { const socialMediaLink = wrapper.find('a').attributes().href expect(socialMediaLink).toBe(socialMediaUrl) }) + + beforeEach(() => { + mocks = { + $t: jest.fn(), + $apollo: { + mutate: jest + .fn() + .mockRejectedValue({ message: 'Ouch!' }) + .mockResolvedValueOnce({ + data: { DeleteSocialMeda: { id: 's1', url: socialMediaUrl } } + }) + }, + $toast: { + error: jest.fn(), + success: jest.fn() + } + } + getters = { + 'auth/user': () => { + return { + socialMedia: [{ id: 's1', url: socialMediaUrl }] + } + } + } + }) + + it('displays a trash sympol after a social media and allows the user to delete it', () => { + wrapper = Wrapper() + const deleteSelector = wrapper.find({ name: 'delete' }) + expect(deleteSelector).toEqual({ selector: 'Component' }) + const icon = wrapper.find({ name: 'trash' }) + icon.trigger('click') + expect(mocks.$apollo.mutate).toHaveBeenCalledTimes(1) + }) }) describe('currentUser does not have a social media account linked', () => { diff --git a/webapp/pages/settings/my-social-media.vue b/webapp/pages/settings/my-social-media.vue index c031f54a4..462e9af96 100644 --- a/webapp/pages/settings/my-social-media.vue +++ b/webapp/pages/settings/my-social-media.vue @@ -8,9 +8,12 @@ - + Social Media link {{ link.url }} +    |    + + + + -
- -
- - {{ $t('settings.social-media.submit') }} - +
+ +
+ + {{ $t('settings.social-media.submit') }} + +
+
@@ -59,13 +75,13 @@ export default { socialMediaLinks() { const { socialMedia = [] } = this.currentUser return socialMedia.map(socialMedia => { - const { url } = socialMedia + const { id, url } = socialMedia const matches = url.match( /^(?:https?:\/\/)?(?:[^@\n])?(?:www\.)?([^:\/\n?]+)/g ) const [domain] = matches || [] const favicon = domain ? `${domain}/favicon.ico` : null - return { url, favicon } + return { id, url, favicon } }) } }, @@ -79,6 +95,7 @@ export default { mutation: gql` mutation($url: String!) { CreateSocialMedia(url: $url) { + id url } } @@ -97,11 +114,51 @@ export default { }) } }) - .then( - this.$toast.success(this.$t('settings.social-media.success')), - (this.value = '') - ) + .then(() => { + this.$toast.success(this.$t('settings.social-media.successAdd')), + (this.value = '') + }) + .catch(error => { + this.$toast.error(error.message) + }) + }, + handleDeleteSocialMedia(link) { + this.$apollo + .mutate({ + mutation: gql` + mutation($id: ID!) { + DeleteSocialMedia(id: $id) { + id + url + } + } + `, + variables: { + id: link.id + }, + update: (store, { data }) => { + const socialMedia = this.currentUser.socialMedia.filter( + element => element.id !== link.id + ) + this.setCurrentUser({ + ...this.currentUser, + socialMedia + }) + } + }) + .then(() => { + this.$toast.success(this.$t('settings.social-media.successDelete')) + }) + .catch(error => { + this.$toast.error(error.message) + }) } } } + +