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

Use async/await in auth store, added tests #88

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
71 changes: 36 additions & 35 deletions src/store/auth.module.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,49 +25,45 @@ const getters = {
};

const actions = {
[LOGIN](context, credentials) {
return new Promise(resolve => {
ApiService.post("users/login", { user: credentials })
.then(({ data }) => {
context.commit(SET_AUTH, data.user);
resolve(data);
})
.catch(({ response }) => {
context.commit(SET_ERROR, response.data.errors);
});
});
async [LOGIN](context, credentials) {
try {
const { data } = await ApiService.post("users/login", {
user: credentials
});
context.commit(SET_AUTH, data.user);
} catch ({ response }) {
context.commit(SET_ERROR, response.data.errors);
throw new Error(response.data.errors);
}
},
[LOGOUT](context) {
context.commit(PURGE_AUTH);
},
[REGISTER](context, credentials) {
return new Promise((resolve, reject) => {
ApiService.post("users", { user: credentials })
.then(({ data }) => {
context.commit(SET_AUTH, data.user);
resolve(data);
})
.catch(({ response }) => {
context.commit(SET_ERROR, response.data.errors);
reject(response);
});
});
async [REGISTER](context, credentials) {
try {
const { data } = await ApiService.post("users", { user: credentials });
context.commit(SET_AUTH, data.user);
} catch ({ response }) {
context.commit(SET_ERROR, response.data.errors);
throw new Error(response.data.errors);
}
},
[CHECK_AUTH](context) {
async [CHECK_AUTH](context) {
if (JwtService.getToken()) {
ApiService.setHeader();
ApiService.get("user")
.then(({ data }) => {
context.commit(SET_AUTH, data.user);
})
.catch(({ response }) => {
context.commit(SET_ERROR, response.data.errors);
});

try {
const { data } = await ApiService.get("user");
context.commit(SET_AUTH, data.user);
} catch ({ response }) {
context.commit(SET_ERROR, response.data.errors);
throw new Error(response.data.errors);
}
} else {
context.commit(PURGE_AUTH);
}
},
[UPDATE_USER](context, payload) {
async [UPDATE_USER](context, payload) {
const { email, username, password, image, bio } = payload;
const user = {
email,
Expand All @@ -79,10 +75,15 @@ const actions = {
user.password = password;
}

return ApiService.put("user", user).then(({ data }) => {
try {
const { data } = await ApiService.put("user", user);
context.commit(SET_AUTH, data.user);
return data;
});

return data.user;
} catch ({ response }) {
context.commit(SET_ERROR, response.data.errors);
throw new Error(response.data.errors);
}
}
};

Expand Down
3 changes: 2 additions & 1 deletion src/views/Login.vue
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ export default {
onSubmit(email, password) {
this.$store
.dispatch(LOGIN, { email, password })
.then(() => this.$router.push({ name: "home" }));
.then(() => this.$router.push({ name: "home" }))
.catch(() => {});
}
},
computed: {
Expand Down
152 changes: 152 additions & 0 deletions tests/unit/store/auth.module.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import auth from "@/store/auth.module";
import { SET_AUTH, PURGE_AUTH, SET_ERROR } from "@/store/mutations.type";
import JwtService from "@/common/jwt.service";
import ApiService from "@/common/api.service";
import {
LOGIN,
LOGOUT,
REGISTER,
CHECK_AUTH,
UPDATE_USER
} from "@/store/actions.type";

jest.mock("@/common/api.service", () => ({
post: jest.fn(),
get: jest.fn(),
put: jest.fn(),
setHeader: jest.fn()
}));

jest.mock("@/common/jwt.service", () => ({
saveToken: jest.fn(),
destroyToken: jest.fn(),
getToken: jest.fn()
}));

describe("getters", () => {
const { getters } = auth;
const state = {
user: "Test User",
isAuthenticated: true
};

it("currentUser", () => {
expect(getters.currentUser(state)).toBe("Test User");
});

it("isAuthenticated", () => {
expect(getters.isAuthenticated(state)).toBe(true);
});
});

describe("mutations", () => {
const { mutations } = auth;
it("SET_ERROR", () => {
const setError = mutations[SET_ERROR];
const state = { errors: null };
setError(state, "Test Error");

expect(state.errors).toBe("Test Error");
});

it("SET_AUTH", () => {
const setAuth = mutations[SET_AUTH];
const state = {
isAuthenticated: false,
user: null,
errors: "Some Error"
};
setAuth(state, { token: "Test Token" });

expect(state).toEqual({
isAuthenticated: true,
user: { token: "Test Token" },
errors: {}
});

expect(JwtService.saveToken).toHaveBeenCalledWith("Test Token");
});

it("PURGE_AUTH", () => {
const purgeAuth = mutations[PURGE_AUTH];
const state = {
isAuthenticated: true,
user: "Test User",
errors: "Some Error"
};
purgeAuth(state);

expect(state).toEqual({
isAuthenticated: false,
user: {},
errors: {}
});

expect(JwtService.destroyToken).toHaveBeenCalled();
});
});

describe("actions", () => {
const { actions } = auth;
let commit;

const userPromise = Promise.resolve({ data: { user: "Test User" } });
ApiService.get.mockReturnValue(userPromise);
ApiService.post.mockReturnValue(userPromise);
ApiService.put.mockReturnValue(userPromise);

beforeEach(() => {
commit = jest.fn();
});

it("LOGIN", done => {
actions[LOGIN]({ commit }, {}).then(() => {
expect(commit).toHaveBeenCalledWith(SET_AUTH, "Test User");
done();
});
});

it("LOGOUT", () => {
actions[LOGOUT]({ commit });
expect(commit).toHaveBeenCalledWith(PURGE_AUTH);
});

it("REGISTER", done => {
actions[REGISTER]({ commit }, {}).then(() => {
expect(commit).toHaveBeenCalledWith(SET_AUTH, "Test User");
done();
});
});

describe("CHECK_AUTH", () => {
it("with token", done => {
JwtService.getToken.mockReturnValueOnce(true);

actions[CHECK_AUTH]({ commit }).then(() => {
expect(commit).toHaveBeenCalledWith(SET_AUTH, "Test User");
done();
});
});

it("without token", () => {
JwtService.getToken.mockReturnValueOnce(false);
actions[CHECK_AUTH]({ commit });
expect(commit).toHaveBeenCalledWith(PURGE_AUTH);
});
});

it("UPDATE_USER", done => {
const testUser = {
email: "[email protected]",
username: "testuser",
password: "testpass123",
image: "test.png",
bio: "Test Bio"
};

actions[UPDATE_USER]({ commit }, testUser).then(() => {
expect(commit).toHaveBeenCalledWith(SET_AUTH, "Test User");
done();
});
});
});
Loading