Open platform to collect and prioritize feedback
Add more e2e tests (#179)
Guilherme Oenning2394f733592f
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.goindex acbc0e073..daa52f5e5 100644--- a/app/pkg/web/context.go+++ b/app/pkg/web/context.go@@ -3,6 +3,7 @@ package webimport ("bytes""encoding/json"+ "net""net/http""strconv""time"@@ -245,6 +246,7 @@ func (ctx *Context) ActiveTransaction() *dbx.Trx {}//BaseURL returns base URL as string+//TODO: missing unit testsfunc (ctx *Context) BaseURL() string {protocol := "http"if ctx.Request.TLS != nil {@@ -254,16 +256,22 @@ func (ctx *Context) BaseURL() string {}//TenantBaseURL returns base URL for a given tenant+//TODO: missing unit testsfunc (ctx *Context) TenantBaseURL(tenant *models.Tenant) string {if env.IsSingleHostMode() {return ctx.BaseURL()}protocol := "http"+ _, port, _ := net.SplitHostPort(ctx.Request.Host)if ctx.Request.TLS != nil {protocol = "https"}- return protocol + "://" + tenant.Subdomain + env.MultiTenantDomain()+ address := protocol + "://" + tenant.Subdomain + env.MultiTenantDomain()+ if port != "" {+ address += ":" + port+ }+ return address}//AuthEndpoint auth endpointdiff --git a/package-lock.json b/package-lock.jsonindex 81bcfd68e..750479234 100644--- a/package-lock.json+++ b/package-lock.json@@ -1139,6 +1139,12 @@"integrity": "sha1-hnqksJP6oF8d4IwG9NeyH9+GmLw=","dev": true},+ "dotenv": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-4.0.0.tgz",+ "integrity": "sha1-hk7xN5rO1Vzm+V3r7NzhefegzR0=",+ "dev": true+ },"ecc-jsbn": {"version": "0.1.1","resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz",diff --git a/package.json b/package.jsonindex 001fb2da2..467914a05 100644--- a/package.json+++ b/package.json@@ -6,7 +6,7 @@"license": "GPL-3.0","scripts": {"build": "rm -rf dist && webpack -p",- "test": "rm -rf output && tsc && mocha -t 30000 output/tsc/tests/**.js",+ "test": "rm -rf output && tsc && mocha -t 30000 output/tsc/tests/testcases/*.js","watch": "rm -rf dist && webpack --watch","lint": "tslint public/**/**.tsx public/**/**.ts"},@@ -25,16 +25,17 @@"throttle-debounce": "^1.0.1"},"devDependencies": {- "@types/react-textarea-autosize": "^4.3.1","@types/jquery": "^3.2.13","@types/markdown-it": "0.0.4","@types/md5": "^2.1.32","@types/mocha": "^2.2.43","@types/react": "^16.0.10","@types/react-dom": "^16.0.0",+ "@types/react-textarea-autosize": "^4.3.1","@types/selenium-webdriver": "^3.0.7","chromedriver": "^2.33.0","css-loader": "^0.28.7",+ "dotenv": "^4.0.0","extract-text-webpack-plugin": "^3.0.1","file-loader": "^1.1.5","mocha": "^4.0.1",diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsxindex d2294b2e6..e7e4f6eaf 100644--- a/public/components/common/SignInControl.tsx+++ b/public/components/common/SignInControl.tsx@@ -86,7 +86,7 @@ export class SignInControl extends React.Component<SignInControlProps, SignInCon{ this.props.signInByEmail && <div><p>Enter your e-mail address to sign in</p><Form ref={(f) => { this.form = f!; } } onSubmit={() => this.signIn() }>- <div className="ui small action fluid input">+ <div id="email-signin" className="ui small action fluid input"><input onChange={(e) => this.setState({ email: e.currentTarget.value }) } type="text" placeholder="[email protected]" className="small" /><button onClick={ () => this.form.submit() } className={`ui small positive button ${this.state.email === '' && 'disabled'}`}>Sign indiff --git a/public/pages/site/CompleteSignInProfilePage.tsx b/public/pages/site/CompleteSignInProfilePage.tsxindex 8258b8326..c39fdde34 100644--- a/public/pages/site/CompleteSignInProfilePage.tsx+++ b/public/pages/site/CompleteSignInProfilePage.tsx@@ -13,12 +13,14 @@ interface CompleteSignInProfilePageState {export class CompleteSignInProfilePage extends React.Component<{}, CompleteSignInProfilePageState> {private form: Form;+ private key: string;@inject(injectables.TenantService)public service: TenantService;constructor(props: {}) {super(props);+ this.key = getQueryString('k');this.state = {name: '',};@@ -29,8 +31,7 @@ export class CompleteSignInProfilePage extends React.Component<{}, CompleteSignI}private async submit() {- const key = getQueryString('k');- const result = await this.service.completeProfile(key, this.state.name);+ const result = await this.service.completeProfile(this.key, this.state.name);if (result.ok) {location.href = '/';} else if (result.error) {diff --git a/public/pages/site/SiteHomePage.tsx b/public/pages/site/SiteHomePage.tsxindex 6a94e92f9..37ecaae4e 100644--- a/public/pages/site/SiteHomePage.tsx+++ b/public/pages/site/SiteHomePage.tsx@@ -63,7 +63,7 @@ export class SiteHomePage extends React.Component<{}, SiteHomePageState> {const search = getQueryString('q');const activeFilter = window.location.hash.substring(1);this.state = {- ideas: this.filterIdeas(activeFilter, search, false),+ ideas: this.filterIdeas(activeFilter, search),showCount: defaultShowCount,activeFilter,searching: !!search,@@ -80,7 +80,7 @@ export class SiteHomePage extends React.Component<{}, SiteHomePageState> {return true;}- private filterIdeas(activeFilter: string, search: string | undefined, push: boolean): Idea[] {+ private filterIdeas(activeFilter: string, search: string | undefined): Idea[] {let newUrl = getBaseUrl();let ideas = [];@@ -100,7 +100,7 @@ export class SiteHomePage extends React.Component<{}, SiteHomePageState> {ideas = IdeaFilter.getFilter(activeFilter)(this.allIdeas);}- if (push && history.replaceState) {+ if (history.replaceState) {window.history.replaceState({ path: newUrl }, '', newUrl);}@@ -109,7 +109,7 @@ export class SiteHomePage extends React.Component<{}, SiteHomePageState> {private filterChanged(name: string) {this.setState({- ideas: this.filterIdeas(name, this.state.search, true),+ ideas: this.filterIdeas(name, this.state.search),showCount: defaultShowCount,activeFilter: name,});@@ -126,14 +126,14 @@ export class SiteHomePage extends React.Component<{}, SiteHomePageState> {this.setState({search: '',searching: false,- ideas: this.filterIdeas(this.state.activeFilter, '', true),+ ideas: this.filterIdeas(this.state.activeFilter, ''),});}private searchIdea(input: string): void {this.setState({search: input,- ideas: this.filterIdeas(this.state.activeFilter, input, true)+ ideas: this.filterIdeas(this.state.activeFilter, input)});}diff --git a/tests/config.ts b/tests/config.tsindex 45df4bd87..e15280e68 100644--- a/tests/config.ts+++ b/tests/config.ts@@ -1,5 +1,5 @@const config = {- baseUrl: process.env.BASE_URL || 'http://demo.dev.fider.io:3000',+ baseUrl: process.env.BASE_URL || 'http://demo.dev.fider.io:3000'};export default config;diff --git a/tests/lib/browser.ts b/tests/lib/browser.tsindex 1e5af9947..194562a8f 100644--- a/tests/lib/browser.ts+++ b/tests/lib/browser.ts@@ -30,6 +30,14 @@ export class Browser {return await this.driver.findElements(By.css(selector));}+ public async switchTo(element: string | WebElement): Promise<void> {+ if (typeof element === 'string') {+ await this.driver.switchTo().frame(this.findElement(element));+ } else {+ return await this.driver.switchTo().frame(element);+ }+ }+public async wait(condition: WaitCondition) {await this.waitAny(condition);}diff --git a/tests/lib/conditions.ts b/tests/lib/conditions.tsindex 9dbb92f10..7058492c0 100644--- a/tests/lib/conditions.ts+++ b/tests/lib/conditions.ts@@ -6,6 +6,10 @@ export function elementIsVisible(locator: () => WebComponent): WaitCondition {return async () => await locator().isDisplayed();}+export function elementIsNotVisible(locator: () => WebComponent): WaitCondition {+ return async () => await locator().isDisplayed() === false;+}+export function elementIsPresent(locator: () => WebComponent): WaitCondition {return async () => await locator() !== undefined;}diff --git a/tests/lib/ensure.ts b/tests/lib/ensure.tsindex 2675eb42b..437f736a8 100644--- a/tests/lib/ensure.ts+++ b/tests/lib/ensure.ts@@ -1,28 +1,50 @@import { WebElementPromise } from 'selenium-webdriver';-import { WebComponent, Button, TextInput } from './';+import { WebComponent, Button, TextInput, delay } from './';class WebComponentEnsurer {+ public async retry(fn: () => Promise<void>) {+ let count = 0;+ let lastErr: Error;+ do {+ try {+ await fn();+ return;+ } catch (err) {+ lastErr = err;+ await delay(500);+ count++;+ }+ } while (count !== 3);+ throw lastErr;+ }+constructor(private component: WebComponent) {}public async textIs(expected: string) {- const text = await this.component.getText();+ await this.retry(async () => {+ const text = await this.component.getText();- if (expected.trim() !== text.trim()) {- throw new Error(`Element ${this.component.selector} text is '${text}'. Expected value is '${expected}'`);- }+ if (expected.trim() !== text.trim()) {+ throw new Error(`Element ${this.component.selector} text is '${text}'. Expected value is '${expected}'`);+ }+ });}public async isVisible() {- if (!await this.component.isDisplayed()) {- throw new Error(`Element ${this.component.selector} is not visible`);- }+ await this.retry(async () => {+ if (!await this.component.isDisplayed()) {+ throw new Error(`Element ${this.component.selector} is not visible`);+ }+ });}public async isNotVisible() {- if (await this.component.isDisplayed()) {- throw new Error(`Element ${this.component.selector} is visible`);- }+ await this.retry(async () => {+ if (await this.component.isDisplayed()) {+ throw new Error(`Element ${this.component.selector} is visible`);+ }+ });}}@@ -34,9 +56,11 @@ class ButtonEnsurer extends WebComponentEnsurer {}public async isNotDisabled() {- if (await this.button.isDisabled()) {- throw new Error(`Button ${this.button.selector} is disabled`);- }+ await this.retry(async () => {+ if (await this.button.isDisabled()) {+ throw new Error(`Button ${this.button.selector} is disabled`);+ }+ });}}diff --git a/tests/lib/index.ts b/tests/lib/index.tsindex 9f2ab2275..3618507ef 100644--- a/tests/lib/index.ts+++ b/tests/lib/index.ts@@ -4,3 +4,4 @@ export * from './utils';export * from './ensure';export * from './components';export * from './conditions';+export * from './mailgun';diff --git a/tests/lib/mailgun/index.ts b/tests/lib/mailgun/index.tsnew file mode 100644index 000000000..44df0f3c1--- /dev/null+++ b/tests/lib/mailgun/index.ts@@ -0,0 +1,41 @@+require('dotenv').config();+import axios from 'axios';+import { delay } from '../';++const mailgunOptions = {+ auth: {+ username: 'api',+ password: process.env.MAILGUN_API!+ }+};++export const mailgun = {+ getLinkFromLastEmailTo: async (to: string): Promise<string> => {+ let messageUrl = '';+ let count = 0;++ do {+ count++;+ const url = `https://api.mailgun.net/v3/${process.env.MAILGUN_DOMAIN}/events?to=${to}&event=accepted&limit=1&ascending=no`;+ const events = await axios.get(url, mailgunOptions);+ if (events.data.items.length > 0 && events.data.items[0].message.headers.to === to) {+ messageUrl = events.data.items[0].storage.url;+ } else {+ delay(2000);+ }+ } while (!messageUrl || count === 3);++ if (count === 3) {+ throw new Error(`Message not found for ${to}.`);+ }++ const message = await axios.get(messageUrl, mailgunOptions);++ const matches = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/.exec(message.data['body-html']);+ if (matches) {+ return matches[2];+ }++ return '';+ }+};diff --git a/tests/lib/page.ts b/tests/lib/page.tsindex 3053742f7..cfb9e52c8 100644--- a/tests/lib/page.ts+++ b/tests/lib/page.ts@@ -5,18 +5,16 @@ export interface NewablePage<T extends Page> {}export abstract class Page {- private url: string;-- protected setUrl(url: string) {- this.url = url;- }public async navigate(): Promise<void> {- await this.browser.navigate(this.url);+ await this.browser.navigate(this.getUrl());await this.browser.wait(this.loadCondition());}public abstract loadCondition(): WaitCondition;+ protected getUrl(): string {+ throw new Error('getUrl not implemented');+ }public constructor(protected browser: Browser) {diff --git a/tests/pages/HomePage.ts b/tests/pages/HomePage.tsindex b35240112..6f8026588 100644--- a/tests/pages/HomePage.ts+++ b/tests/pages/HomePage.ts@@ -1,4 +1,4 @@-import { WebComponent, Browser, Page, findBy, findMultipleBy, Button, TextInput, elementIsVisible, pageHasLoaded } from '../lib';+import { WebComponent, Browser, Page, findBy, findMultipleBy, Button, TextInput, elementIsVisible, elementIsNotVisible, pageHasLoaded } from '../lib';import { ShowIdeaPage, GoogleSignInPage, FacebookSignInPage } from './';import config from '../config';import { tenant } from '../context';@@ -8,7 +8,10 @@ import { IdeaList } from '../components/IdeaList';export class HomePage extends Page {constructor(browser: Browser) {super(browser);- this.setUrl(`http://${tenant}.dev.fider.io:3000/`);+ }++ public getUrl(): string {+ return `http://${tenant}.dev.fider.io:3000/`;}@findBy('#new-idea-input')@@ -35,6 +38,12 @@ export class HomePage extends Page {@findBy('#signin-modal .button.facebook')public FacebookSignIn: Button;+ @findBy('#email-signin input')+ private EmailSignInInput: TextInput;++ @findBy('#email-signin button')+ private EmailSignInButton: TextInput;+@findBy('.ui.form .ui.negative.message')public ErrorBox: WebComponent;@@ -44,6 +53,12 @@ export class HomePage extends Page {@findMultipleBy('.fdr-idea-list > .item')public IdeaList: IdeaList;+ @findBy('#signin-complete-modal input')+ private CompleteEmailSignInInput: TextInput;++ @findBy('#signin-complete-modal button')+ private CompleteEmailSignInButton: Button;+public loadCondition() {return elementIsVisible(() => this.IdeaTitle);}@@ -86,7 +101,25 @@ export class HomePage extends Page {]);}- public async signIn(locator: () => WebComponent): Promise<void> {+ public async signInWithEmail(email: string): Promise<void> {+ await this.signOut();+ await this.UserMenu.click();+ await this.browser.wait(elementIsVisible(() => this.EmailSignInInput));+ await this.EmailSignInInput.type(email);+ await this.EmailSignInButton.click();+ await this.browser.wait(+ elementIsNotVisible(() => this.EmailSignInButton)+ );+ }++ public async completeSignIn(name: string): Promise<void> {+ await this.browser.wait(elementIsVisible(() => this.CompleteEmailSignInInput));+ await this.CompleteEmailSignInInput.type(name);+ await this.CompleteEmailSignInButton.click();+ await this.browser.wait(this.loadCondition());+ }++ private async signIn(locator: () => WebComponent): Promise<void> {await this.UserMenu.click();await this.browser.wait(elementIsVisible(locator));await locator().click();diff --git a/tests/pages/SignUpPage.ts b/tests/pages/SignUpPage.tsindex 735785177..32bac677d 100644--- a/tests/pages/SignUpPage.ts+++ b/tests/pages/SignUpPage.ts@@ -4,7 +4,10 @@ import { GoogleSignInPage, FacebookSignInPage, HomePage } from './';export class SignUpPage extends Page {constructor(browser: Browser) {super(browser);- this.setUrl('http://login.dev.fider.io:3000/signup');+ }++ public getUrl(): string {+ return `http://login.dev.fider.io:3000/signup`;}@findBy('#fdr-signup-page')@@ -16,6 +19,12 @@ export class SignUpPage extends Page {@findBy('#fdr-signup-page .button.facebook')public FacebookSignIn: Button;+ @findBy('#fdr-signup-page .form #name')+ public UserName: TextInput;++ @findBy('#fdr-signup-page .form #email')+ public UserEmail: TextInput;+@findBy('#fdr-signup-page .form #tenantName')public TenantName: TextInput;@@ -28,6 +37,9 @@ export class SignUpPage extends Page {@findBy('#fdr-signup-page .page .green.basic.label')private SubdomainOk: WebComponent;+ @findBy('#submitted-modal')+ private SubmitConfirmation: WebComponent;+public loadCondition() {return elementIsVisible(() => this.Container);}@@ -42,11 +54,19 @@ export class SignUpPage extends Page {await this.browser.wait(pageHasLoaded(FacebookSignInPage));}+ public async signInWithEmail(name: string, email: string): Promise<void> {+ await this.UserName.type(name);+ await this.UserEmail.type(email);+ }+public async signUpAs(name: string, subdomain: string): Promise<void> {await this.TenantName.type(name);await this.Subdomain.type(subdomain);await this.browser.wait(elementIsVisible(() => this.SubdomainOk));await this.Confirm.click();- await this.browser.wait(pageHasLoaded(HomePage));+ await this.browser.waitAny([+ pageHasLoaded(HomePage),+ elementIsVisible(() => this.SubmitConfirmation)+ ]);}}diff --git a/tests/pages/index.ts b/tests/pages/index.tsindex 1d3d9b209..a5e96b11f 100644--- a/tests/pages/index.ts+++ b/tests/pages/index.ts@@ -28,6 +28,10 @@ export class AllPages {this.showIdea = new ShowIdeaPage(browser);}+ public async goTo(url: string): Promise<void> {+ return this.browser.navigate(url);+ }+public async dispose(): Promise<void> {await this.browser.close();}diff --git a/tests/setup.ts b/tests/setup.tsdeleted file mode 100644index 7d3e08a79..000000000--- a/tests/setup.ts+++ /dev/null@@ -1,29 +0,0 @@-import { Browser } from './lib';-import { AllPages } from './pages';-import { setPages, setBrowser, setTenant } from './context';--let browser: Browser;-let pages: AllPages;--before(async () => {- const now = new Date().getTime();- const tenantName = `Selenium ${now}`;- const tenantSubdomain = `selenium${now}`;- setTenant(tenantSubdomain);-- browser = new Browser('chrome');- pages = new AllPages(browser);-- await pages.signup.navigate();- await pages.signup.signInWithFacebook();- await pages.facebook.signInAsJonSnow();-- await pages.signup.signUpAs(tenantName, tenantSubdomain);-- setBrowser(browser);- setPages(pages);-});--after(async () => {- await pages.dispose();-});diff --git a/tests/testcases/SignUpByEmail.ts b/tests/testcases/SignUpByEmail.tsnew file mode 100644index 000000000..eafc83db9--- /dev/null+++ b/tests/testcases/SignUpByEmail.ts@@ -0,0 +1,31 @@+import { ensure, elementIsVisible, mailgun, delay } from '../lib';+import { pages, tenant, browser } from '../context';+import { initialize } from './setup';++describe('Sign up by e-mail', () => {+ before(async () => {+ initialize();+ });++ after(async () => {+ await pages.dispose();+ });++ it('User can sign up using e-mail', async () => {+ const now = new Date().getTime();++ // Action+ await pages.signup.navigate();+ await pages.signup.signInWithEmail(`Darth Vader ${now}`, `darthvader.fider+${now}@gmail.com`);+ await pages.signup.signUpAs(`Selenium ${now}`, `selenium${now}`);++ const link = await mailgun.getLinkFromLastEmailTo(`darthvader.fider+${now}@gmail.com`);++ await pages.goTo(link);+ await browser.wait(pages.home.loadCondition());++ // Assert+ await pages.home.UserMenu.click();+ await ensure(pages.home.UserName).textIs(`DARTH VADER ${now}`);+ });+});diff --git a/tests/submit-ideas.ts b/tests/testcases/SubmitIdeas.tssimilarity index 66%rename from tests/submit-ideas.tsrename to tests/testcases/SubmitIdeas.tsindex d6c45efeb..bd2566ed2 100644--- a/tests/submit-ideas.ts+++ b/tests/testcases/SubmitIdeas.ts@@ -1,8 +1,17 @@-import { ensure, elementIsVisible } from './lib';-import { pages, tenant, browser } from './context';+import { ensure, elementIsVisible, mailgun } from '../lib';+import { pages, tenant, browser } from '../context';+import { createTenant } from './setup';describe('Submit ideas', () => {+ before(async () => {+ await createTenant();+ });++ after(async () => {+ await pages.dispose();+ });+it('User is authenticated after sign up', async () => {// Actionawait pages.home.navigate();@@ -56,4 +65,23 @@ describe('Submit ideas', () => {await pages.home.IdeaList.want(0);await ensure(await pages.home.IdeaList.at(0)).textIs('2');});++ it('User can sign in using e-mail on existing tenant', async () => {+ const now = new Date().getTime();++ // Action+ await pages.home.navigate();+ await pages.home.signInWithEmail(`darthvader.fider+${now}@gmail.com`);++ const link = await mailgun.getLinkFromLastEmailTo(`darthvader.fider+${now}@gmail.com`);++ await pages.goTo(link);+ await browser.wait(pages.home.loadCondition());++ await pages.home.completeSignIn(`Darth Vader ${now}`);++ // Assert+ await pages.home.UserMenu.click();+ await ensure(pages.home.UserName).textIs(`DARTH VADER ${now}`);+ });});diff --git a/tests/testcases/setup.ts b/tests/testcases/setup.tsnew file mode 100644index 000000000..f7512653d--- /dev/null+++ b/tests/testcases/setup.ts@@ -0,0 +1,30 @@+import { ensure, Browser } from '../lib';+import { AllPages } from '../pages';+import { setPages, setBrowser, setTenant } from '../context';++export function initialize() {+ const browser = new Browser('chrome');+ const pages = new AllPages(browser);++ setBrowser(browser);+ setPages(pages);+}++export async function createTenant() {+ const now = new Date().getTime();+ const tenantName = `Selenium ${now}`;+ const tenantSubdomain = `selenium${now}`;+ setTenant(tenantSubdomain);++ const browser = new Browser('chrome');+ const pages = new AllPages(browser);++ setBrowser(browser);+ setPages(pages);++ await pages.signup.navigate();+ await pages.signup.signInWithFacebook();+ await pages.facebook.signInAsJonSnow();++ await pages.signup.signUpAs(tenantName, tenantSubdomain);+}