Merge branch 'tests'

This commit is contained in:
canove
2020-10-24 16:35:34 -03:00
20 changed files with 572 additions and 117 deletions

View File

@@ -1,7 +1,8 @@
{
"env": {
"es2021": true,
"node": true
"node": true,
"jest": true
},
"extends": [
"airbnb-base",
@@ -16,6 +17,7 @@
},
"plugins": ["@typescript-eslint", "prettier"],
"rules": {
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{ "argsIgnorePattern": "_" }

5
backend/.gitignore vendored
View File

@@ -3,9 +3,14 @@ public/*
dist
!public/.gitkeep
.env
.env.test
package-lock.json
yarn.lock
yarn-error.log
/src/config/sentry.js
# Ignore test-related files
/coverage.data
/coverage/

186
backend/jest.config.js Normal file
View File

@@ -0,0 +1,186 @@
/*
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/en/configuration.html
*/
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
bail: 1,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/tmp/jest_rs",
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: ["<rootDir>/src/services/**/*.ts"],
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: ["text", "lcov"],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
preset: "ts-jest",
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: ["**/__tests__/**/*.spec.ts"]
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};

View File

@@ -7,7 +7,10 @@
"build": "tsc",
"watch": "tsc -w",
"start": "nodemon dist/server.js",
"dev:server": "ts-node-dev --respawn --transpile-only --ignore node_modules src/server.ts"
"dev:server": "ts-node-dev --respawn --transpile-only --ignore node_modules src/server.ts",
"pretest": "NODE_ENV=test sequelize db:migrate && NODE_ENV=test sequelize db:seed:all",
"test": "NODE_ENV=test jest",
"posttest": "NODE_ENV=test sequelize db:migrate:undo:all"
},
"author": "",
"license": "MIT",
@@ -39,10 +42,14 @@
"@types/cookie-parser": "^1.4.2",
"@types/cors": "^2.8.7",
"@types/express": "^4.17.8",
"@types/factory-girl": "^5.0.2",
"@types/faker": "^5.1.3",
"@types/jest": "^26.0.15",
"@types/jsonwebtoken": "^8.5.0",
"@types/multer": "^1.4.4",
"@types/node": "^14.11.8",
"@types/socket.io": "^2.1.11",
"@types/supertest": "^2.0.10",
"@types/validator": "^13.1.0",
"@types/yup": "^0.29.8",
"@typescript-eslint/eslint-plugin": "^4.4.0",
@@ -53,8 +60,13 @@
"eslint-import-resolver-typescript": "^2.3.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-prettier": "^3.1.4",
"factory-girl": "^5.0.4",
"faker": "^5.1.0",
"jest": "^26.6.0",
"nodemon": "^2.0.4",
"prettier": "^2.1.2",
"supertest": "^5.0.0",
"ts-jest": "^26.4.1",
"ts-node-dev": "^1.0.0-pre.63",
"typescript": "^4.0.3"
}

View File

@@ -0,0 +1,66 @@
import faker from "faker";
import AppError from "../../../errors/AppError";
import AuthUserService from "../../../services/UserServices/AuthUserSerice";
import CreateUserService from "../../../services/UserServices/CreateUserService";
import { disconnect, truncate } from "../../utils/database";
describe("Auth", () => {
beforeEach(async () => {
await truncate();
});
afterEach(async () => {
await truncate();
});
afterAll(async () => {
await disconnect();
});
it("should be able to login with an existing user", async () => {
await CreateUserService({
name: faker.name.findName(),
email: "mail@test.com",
password: "hardpassword"
});
const response = await AuthUserService({
email: "mail@test.com",
password: "hardpassword"
});
expect(response).toHaveProperty("token");
});
it("should not be able to login with not registered email", async () => {
try {
await AuthUserService({
email: faker.internet.email(),
password: faker.internet.password()
});
} catch (err) {
expect(err).toBeInstanceOf(AppError);
expect(err.statusCode).toBe(401);
expect(err.message).toBe("ERR_INVALID_CREDENTIALS");
}
});
it("should not be able to login with incorret password", async () => {
await CreateUserService({
name: faker.name.findName(),
email: "mail@test.com",
password: "hardpassword"
});
try {
await AuthUserService({
email: "mail@test.com",
password: faker.internet.password()
});
} catch (err) {
expect(err).toBeInstanceOf(AppError);
expect(err.statusCode).toBe(401);
expect(err.message).toBe("ERR_INVALID_CREDENTIALS");
}
});
});

View File

@@ -0,0 +1,47 @@
import faker from "faker";
import AppError from "../../../errors/AppError";
import CreateUserService from "../../../services/UserServices/CreateUserService";
import { disconnect, truncate } from "../../utils/database";
describe("User", () => {
beforeEach(async () => {
await truncate();
});
afterEach(async () => {
await truncate();
});
afterAll(async () => {
await disconnect();
});
it("should be able to create a new user", async () => {
const user = await CreateUserService({
name: faker.name.findName(),
email: faker.internet.email(),
password: faker.internet.password()
});
expect(user).toHaveProperty("id");
});
it("should not be able to create a user with duplicated email", async () => {
await CreateUserService({
name: faker.name.findName(),
email: "teste@sameemail.com",
password: faker.internet.password()
});
try {
await CreateUserService({
name: faker.name.findName(),
email: "teste@sameemail.com",
password: faker.internet.password()
});
} catch (err) {
expect(err).toBeInstanceOf(AppError);
expect(err.statusCode).toBe(400);
}
});
});

View File

@@ -0,0 +1,35 @@
import faker from "faker";
import AppError from "../../../errors/AppError";
import CreateUserService from "../../../services/UserServices/CreateUserService";
import DeleteUserService from "../../../services/UserServices/DeleteUserService";
import { disconnect, truncate } from "../../utils/database";
describe("User", () => {
beforeEach(async () => {
await truncate();
});
afterEach(async () => {
await truncate();
});
afterAll(async () => {
await disconnect();
});
it("should be delete a existing user", async () => {
const { id } = await CreateUserService({
name: faker.name.findName(),
email: faker.internet.email(),
password: faker.internet.password()
});
expect(DeleteUserService(id)).resolves.not.toThrow();
});
it("to throw an error if tries to delete a non existing user", async () => {
expect(DeleteUserService(faker.random.number())).rejects.toBeInstanceOf(
AppError
);
});
});

View File

@@ -0,0 +1,34 @@
import faker from "faker";
import User from "../../../models/User";
import CreateUserService from "../../../services/UserServices/CreateUserService";
import ListUsersService from "../../../services/UserServices/ListUsersService";
import { disconnect, truncate } from "../../utils/database";
describe("User", () => {
beforeEach(async () => {
await truncate();
});
afterEach(async () => {
await truncate();
});
afterAll(async () => {
await disconnect();
});
it("should be able to list users", async () => {
await CreateUserService({
name: faker.name.findName(),
email: faker.internet.email(),
password: faker.internet.password()
});
const response = await ListUsersService({
pageNumber: 1
});
expect(response).toHaveProperty("users");
expect(response.users[0]).toBeInstanceOf(User);
});
});

View File

@@ -0,0 +1,39 @@
import faker from "faker";
import AppError from "../../../errors/AppError";
import User from "../../../models/User";
import CreateUserService from "../../../services/UserServices/CreateUserService";
import ShowUserService from "../../../services/UserServices/ShowUserService";
import { disconnect, truncate } from "../../utils/database";
describe("User", () => {
beforeEach(async () => {
await truncate();
});
afterEach(async () => {
await truncate();
});
afterAll(async () => {
await disconnect();
});
it("should be able to find a user", async () => {
const newUser = await CreateUserService({
name: faker.name.findName(),
email: faker.internet.email(),
password: faker.internet.password()
});
const user = await ShowUserService(newUser.id);
expect(user).toHaveProperty("id");
expect(user).toBeInstanceOf(User);
});
it("should not be able to find a inexisting user", async () => {
expect(ShowUserService(faker.random.number())).rejects.toBeInstanceOf(
AppError
);
});
});

View File

@@ -0,0 +1,68 @@
import faker from "faker";
import AppError from "../../../errors/AppError";
import CreateUserService from "../../../services/UserServices/CreateUserService";
import UpdateUserService from "../../../services/UserServices/UpdateUserService";
import { disconnect, truncate } from "../../utils/database";
describe("User", () => {
beforeEach(async () => {
await truncate();
});
afterEach(async () => {
await truncate();
});
afterAll(async () => {
await disconnect();
});
it("should be able to find a user", async () => {
const newUser = await CreateUserService({
name: faker.name.findName(),
email: faker.internet.email(),
password: faker.internet.password()
});
const updatedUser = await UpdateUserService({
userId: newUser.id,
userData: {
name: "New name",
email: "newmail@email.com"
}
});
expect(updatedUser).toHaveProperty("name", "New name");
expect(updatedUser).toHaveProperty("email", "newmail@email.com");
});
it("should not be able to updated a inexisting user", async () => {
const userId = faker.random.number();
const userData = {
name: faker.name.findName(),
email: faker.internet.email()
};
expect(UpdateUserService({ userId, userData })).rejects.toBeInstanceOf(
AppError
);
});
it("should not be able to updated an user with invalid data", async () => {
const newUser = await CreateUserService({
name: faker.name.findName(),
email: faker.internet.email(),
password: faker.internet.password()
});
const userId = newUser.id;
const userData = {
name: faker.name.findName(),
email: "test.worgn.email"
};
expect(UpdateUserService({ userId, userData })).rejects.toBeInstanceOf(
AppError
);
});
});

View File

@@ -0,0 +1,11 @@
import database from "../../database";
const truncate = async (): Promise<void> => {
await database.truncate({ force: true, cascade: true });
};
const disconnect = async (): Promise<void> => {
return database.connectionManager.close();
};
export { truncate, disconnect };

41
backend/src/app.ts Normal file
View File

@@ -0,0 +1,41 @@
import "./bootstrap";
import "reflect-metadata";
import "express-async-errors";
import express, { Request, Response, NextFunction } from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import * as Sentry from "@sentry/node";
import "./database";
import uploadConfig from "./config/upload";
import AppError from "./errors/AppError";
import routes from "./routes";
Sentry.init({ dsn: process.env.SENTRY_DSN });
const app = express();
app.use(
cors({
credentials: true,
origin: process.env.FRONTEND_URL
})
);
app.use(cookieParser());
app.use(express.json());
app.use(Sentry.Handlers.requestHandler());
app.use("/public", express.static(uploadConfig.directory));
app.use(routes);
app.use(Sentry.Handlers.errorHandler());
app.use(async (err: Error, req: Request, res: Response, _: NextFunction) => {
if (err instanceof AppError) {
return res.status(err.statusCode).json({ error: err.message });
}
console.error(err);
return res.status(500).json({ error: "Internal server error" });
});
export default app;

5
backend/src/bootstrap.ts Normal file
View File

@@ -0,0 +1,5 @@
import dotenv from "dotenv";
dotenv.config({
path: process.env.NODE_ENV === "test" ? ".env.test" : ".env"
});

View File

@@ -1,4 +1,4 @@
require("dotenv/config");
require("../bootstrap");
module.exports = {
define: {

View File

@@ -1,48 +1,10 @@
import "reflect-metadata";
import "dotenv/config";
import "express-async-errors";
import express, { Request, Response, NextFunction } from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import * as Sentry from "@sentry/node";
import uploadConfig from "./config/upload";
import "./database";
import AppError from "./errors/AppError";
import routes from "./routes";
import app from "./app";
import { initIO } from "./libs/socket";
import { StartWhatsAppSessions } from "./services/WbotServices/StartWhatsAppSessions";
Sentry.init({ dsn: process.env.SENTRY_DSN });
const app = express();
app.use(
cors({
credentials: true,
origin: process.env.FRONTEND_URL
})
);
app.use(cookieParser());
app.use(express.json());
app.use(Sentry.Handlers.requestHandler());
app.use("/public", express.static(uploadConfig.directory));
app.use(routes);
const server = app.listen(process.env.PORT, () => {
console.log(`Server started on port: ${process.env.PORT}`);
});
initIO(server);
StartWhatsAppSessions();
app.use(Sentry.Handlers.errorHandler());
app.use(async (err: Error, req: Request, res: Response, _: NextFunction) => {
if (err instanceof AppError) {
return res.status(err.statusCode).json({ error: err.message });
}
console.error(err);
return res.status(500).json({ error: "Internal server error" });
});

View File

@@ -32,13 +32,10 @@ const CreateUserService = async ({
"Check-email",
"An user with this email already exists.",
async value => {
if (value) {
const emailExists = await User.findOne({
where: { email: value }
});
return !emailExists;
}
return false;
const emailExists = await User.findOne({
where: { email: value! }
});
return !emailExists;
}
),
password: Yup.string().required().min(5)

View File

@@ -3,7 +3,7 @@ import AppError from "../../errors/AppError";
import Ticket from "../../models/Ticket";
import UpdateDeletedUserOpenTicketsStatus from "../../helpers/UpdateDeletedUserOpenTicketsStatus";
const DeleteUserService = async (id: string): Promise<void> => {
const DeleteUserService = async (id: string | number): Promise<void> => {
const user = await User.findOne({
where: { id }
});

View File

@@ -3,7 +3,7 @@ import User from "../../models/User";
interface Request {
searchParam?: string;
pageNumber?: string;
pageNumber?: string | number;
}
interface Response {

View File

@@ -12,7 +12,7 @@ interface UserData {
interface Request {
userData: UserData;
userId: string;
userId: string | number;
}
interface Response {

View File

@@ -1,69 +1,14 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
"strictPropertyInitialization": false /* Enable strict checking of property initialization in classes. */,
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
"experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
"emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"strictPropertyInitialization": false,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}