Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor files 61-70 in tests/resolvers/Mutation [Fixes #989] #1014

Merged
merged 30 commits into from
Feb 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
a453b62
Create test for resolvers/Query/index.spec.ts
anshgoyalevil Jan 29, 2023
f3e2ce1
Update index.spec.ts
anshgoyalevil Jan 29, 2023
20251eb
Create test for roleDirective.ts
anshgoyalevil Jan 29, 2023
44b39c2
Merge branch 'PalisadoesFoundation:develop' into develop
anshgoyalevil Jan 29, 2023
41a41f5
Merge branch 'PalisadoesFoundation:develop' into develop
anshgoyalevil Jan 30, 2023
429e06e
feat: use constants instead of env
anshgoyalevil Jan 30, 2023
8f5d2d1
Merge branch 'PalisadoesFoundation:develop' into develop
anshgoyalevil Jan 31, 2023
a6419f3
create directives/index.spec.ts
anshgoyalevil Jan 31, 2023
2be872d
Merge branch 'PalisadoesFoundation:develop' into develop
anshgoyalevil Feb 1, 2023
f42253f
Merge branch 'PalisadoesFoundation:develop' into develop
anshgoyalevil Feb 1, 2023
a1dbabf
refactor: update DirectChatMessage
anshgoyalevil Feb 1, 2023
214f58a
update some files
anshgoyalevil Feb 1, 2023
35c3701
add otp.ts
anshgoyalevil Feb 1, 2023
97c1876
update some files
anshgoyalevil Feb 1, 2023
d56990a
refactor: refactored GroupChat files
anshgoyalevil Feb 1, 2023
e0ef8bc
Merge branch 'PalisadoesFoundation:develop' into develop
anshgoyalevil Feb 2, 2023
02f916b
remove duplicate helper and refactor utilities
anshgoyalevil Feb 2, 2023
da7ccc5
Merge branch 'PalisadoesFoundation:develop' into develop
anshgoyalevil Feb 3, 2023
29e987d
Merge branch 'PalisadoesFoundation:develop' into develop
anshgoyalevil Feb 3, 2023
6095d86
refactor acceptAdmin.spec.ts
anshgoyalevil Feb 3, 2023
a4bc38e
Merge branch 'PalisadoesFoundation:develop' into develop
anshgoyalevil Feb 4, 2023
5308100
refactor 20 tests in mutation
anshgoyalevil Feb 4, 2023
549d992
fix createAdmin.spec.ts tests
anshgoyalevil Feb 4, 2023
9261208
fix blockUser.spec.ts
anshgoyalevil Feb 4, 2023
d8ae6cf
refactor remaining files in 1-20 range
anshgoyalevil Feb 4, 2023
6a8fdd0
refactor mutation folder 21-40 files
anshgoyalevil Feb 5, 2023
7f72266
Merge branch 'PalisadoesFoundation:develop' into develop
anshgoyalevil Feb 5, 2023
327807c
add test for authDirective.ts
anshgoyalevil Feb 5, 2023
90c20ee
refactor files 61-70 in tests/Mutation
anshgoyalevil Feb 6, 2023
e32280a
Re-run Workflow Trigger
anshgoyalevil Feb 6, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 175 additions & 0 deletions tests/directives/authDirective.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { AuthenticationDirective } from "../../src/directives/authDirective";
import { beforeAll, afterAll, it, expect } from "vitest";
import { connect, disconnect } from "../../src/db";
import { ApolloServer, gql } from "apollo-server-express";
import { errors } from "../../src/libraries";
import "dotenv/config";
import i18n from "i18n";
import express from "express";
import { appConfig } from "../../src/config";
import { testUserType } from "../helpers/userAndOrg";
import { createTestUserFunc } from "../helpers/user";

const app = express();
i18n.configure({
directory: `${__dirname}/locales`,
staticCatalog: {
en: require("../../locales/en.json"),
hi: require("../../locales/hi.json"),
zh: require("../../locales/zh.json"),
sp: require("../../locales/sp.json"),
fr: require("../../locales/fr.json"),
},
queryParameter: "lang",
defaultLocale: appConfig.defaultLocale,
locales: appConfig.supportedLocales,
autoReload: process.env.NODE_ENV !== "production",
updateFiles: process.env.NODE_ENV !== "production",
syncFiles: process.env.NODE_ENV !== "production",
});
app.use(i18n.init);

let testUser: testUserType;

const typeDefs = gql`
directive @auth on FIELD_DEFINITION

type Query {
hello: String @auth
}
`;

const resolvers = {
Query: {
hello: async () => "hi",
},
};

beforeAll(async () => {
await connect();
testUser = await createTestUserFunc();
});

afterAll(async () => {
await testUser!.remove();
await disconnect();
});

it("throws UnauthenticatedError when context is expired", async () => {
const query = `
query {
hello
}
`;
const authenticatedContext = {
expired: true,
};
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
schemaDirectives: {
auth: AuthenticationDirective,
},
context: authenticatedContext,
});
apolloServer.applyMiddleware({
app,
});
try {
await apolloServer.executeOperation({
query,
variables: {},
});
} catch (err) {
if (err instanceof errors.UnauthenticatedError) {
expect(err.message).toEqual("user.notAuthenticated");
}
}
});

it("throws UnauthenticatedError when context: isAuth == false", async () => {
const query = `
query {
hello
}
`;
const authenticatedContext = {
isAuth: false,
};
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
schemaDirectives: {
auth: AuthenticationDirective,
},
context: authenticatedContext,
});
apolloServer.applyMiddleware({
app,
});
try {
await apolloServer.executeOperation({
query,
variables: {},
});
} catch (err) {
if (err instanceof errors.UnauthenticatedError) {
expect(err.message).toEqual("user.notAuthenticated");
}
}
});

it("checks if the resolver is supplied, and return null data, if not", async () => {
const query = `
query {
hello
}
`;
const authenticatedContext = {
expired: true,
isAuth: false,
};
const apolloServer = new ApolloServer({
typeDefs,
schemaDirectives: {
auth: AuthenticationDirective,
},
context: authenticatedContext,
});
apolloServer.applyMiddleware({
app,
});
const result = await apolloServer.executeOperation({
query,
variables: {},
});
expect(result.data).toEqual({ hello: null });
});

it("returns data if isAuth == true and expire == false", async () => {
const query = `
query {
hello
}
`;
const authenticatedContext = {
expired: false,
isAuth: true,
};
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
schemaDirectives: {
auth: AuthenticationDirective,
},
context: authenticatedContext,
});
apolloServer.applyMiddleware({
app,
});
const result = await apolloServer.executeOperation({
query,
variables: {},
});
expect(result.data).toEqual({ hello: "hi" });
});
8 changes: 4 additions & 4 deletions tests/helpers/eventsWithRegistrants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ export type testEventType =
| (Interface_Event & Document<any, any, Interface_Event>)
| null;

export const createTestEventWithRegistrants = async (): Promise<
[testUserType, testOrganizationType, testEventType]
> => {
export const createTestEventWithRegistrants = async (
isAdmin = true
): Promise<[testUserType, testOrganizationType, testEventType]> => {
const resultsArray = await createTestUserAndOrganization();
const testUser = resultsArray[0];
const testOrganization = resultsArray[1];
Expand Down Expand Up @@ -42,7 +42,7 @@ export const createTestEventWithRegistrants = async (): Promise<
},
{
$push: {
eventAdmin: testEvent._id,
eventAdmin: isAdmin ? testEvent._id : [],
createdEvents: testEvent._id,
registeredEvents: testEvent._id,
},
Expand Down
97 changes: 22 additions & 75 deletions tests/resolvers/Mutation/unregisterForEventByUser.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import "dotenv/config";
import { Document, Types } from "mongoose";
import {
Interface_User,
User,
Organization,
Event,
Interface_Event,
} from "../../../src/models";
import { Types } from "mongoose";
import { User, Event } from "../../../src/models";
import { MutationUnregisterForEventByUserArgs } from "../../../src/types/generatedGraphQLTypes";
import { connect, disconnect } from "../../../src/db";
import { unregisterForEventByUser as unregisterForEventByUserResolver } from "../../../src/resolvers/Mutation/unregisterForEventByUser";
Expand All @@ -15,65 +9,18 @@ import {
USER_ALREADY_UNREGISTERED,
USER_NOT_FOUND,
} from "../../../src/constants";
import { nanoid } from "nanoid";
import { beforeAll, afterAll, describe, it, expect } from "vitest";
import { testUserType } from "../../helpers/userAndOrg";
import { createTestEvent, testEventType } from "../../helpers/events";

let testUser: Interface_User & Document<any, any, Interface_User>;
let testEvent: Interface_Event & Document<any, any, Interface_Event>;
let testUser: testUserType;
let testEvent: testEventType;

beforeAll(async () => {
await connect();

testUser = await User.create({
email: `email${nanoid().toLowerCase()}@gmail.com`,
password: "password",
firstName: "firstName",
lastName: "lastName",
appLanguageCode: "en",
});

const testOrganization = await Organization.create({
name: "name",
description: "description",
isPublic: true,
creator: testUser._id,
members: [testUser._id],
visibleInSearch: true,
});

await User.updateOne(
{
_id: testUser._id,
},
{
$set: {
createdOrganizations: [testOrganization._id],
joinedOrganizations: [testOrganization._id],
},
}
);

testEvent = await Event.create({
creator: testUser._id,
organization: testOrganization._id,
isRegisterable: true,
isPublic: true,
title: "title",
description: "description",
allDay: true,
startDate: new Date().toString(),
});

await User.updateOne(
{
_id: testUser._id,
},
{
$set: {
createdEvents: [testEvent._id],
},
}
);
const temp = await createTestEvent();
testUser = temp[0];
testEvent = temp[2];
});

afterAll(async () => {
Expand Down Expand Up @@ -104,7 +51,7 @@ describe("resolvers -> Mutation -> unregisterForEventByUser", () => {
};

const context = {
userId: testUser._id,
userId: testUser!._id,
};

await unregisterForEventByUserResolver?.({}, args, context);
Expand All @@ -117,11 +64,11 @@ describe("resolvers -> Mutation -> unregisterForEventByUser", () => {
not a registrant of event with _id === args.id`, async () => {
try {
const args: MutationUnregisterForEventByUserArgs = {
id: testEvent._id,
id: testEvent!._id,
};

const context = {
userId: testUser._id,
userId: testUser!._id,
};

await unregisterForEventByUserResolver?.({}, args, context);
Expand All @@ -134,13 +81,13 @@ describe("resolvers -> Mutation -> unregisterForEventByUser", () => {
_id === args.id`, async () => {
await Event.updateOne(
{
_id: testEvent._id,
_id: testEvent!._id,
},
{
$push: {
registrants: {
userId: testUser._id,
user: testUser._id,
userId: testUser!._id,
user: testUser!._id,
status: "ACTIVE",
},
},
Expand All @@ -149,28 +96,28 @@ describe("resolvers -> Mutation -> unregisterForEventByUser", () => {

await User.updateOne(
{
_id: testUser._id,
_id: testUser!._id,
},
{
$push: {
registeredEvents: testEvent._id,
registeredEvents: testEvent!._id,
},
}
);

const args: MutationUnregisterForEventByUserArgs = {
id: testEvent._id,
id: testEvent!._id,
};

const context = {
userId: testUser._id,
userId: testUser!._id,
};

const unregisterForEventByUserPayload =
await unregisterForEventByUserResolver?.({}, args, context);

const testUnregisterForEventByUserPayload = await Event.findOne({
_id: testEvent._id,
_id: testEvent!._id,
}).lean();

expect(unregisterForEventByUserPayload).toEqual(
Expand All @@ -182,11 +129,11 @@ describe("resolvers -> Mutation -> unregisterForEventByUser", () => {
already unregistered from the event with _id === args.id`, async () => {
try {
const args: MutationUnregisterForEventByUserArgs = {
id: testEvent._id,
id: testEvent!._id,
};

const context = {
userId: testUser._id,
userId: testUser!._id,
};

await unregisterForEventByUserResolver?.({}, args, context);
Expand Down
Loading