Skip to content

Commit

Permalink
refactor: optimize tests
Browse files Browse the repository at this point in the history
  • Loading branch information
supersonictw committed Oct 26, 2024
1 parent 5ad4ce9 commit af3b7dc
Show file tree
Hide file tree
Showing 3 changed files with 160 additions and 116 deletions.
113 changes: 73 additions & 40 deletions test/kernel/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,75 @@ const {StatusCodes} = require("http-status-codes");
const {useApp} = require("../../src/init/express");
const {useCache} = require("../../src/init/cache");

/**
* Print message with testing notification.
* @param {any} messages
*/
function print(...messages) {
if (isProduction()) return;
const timestamp = new Date().toString();
console.timeStamp(
"---\n",
"[!] *Test mode*\n",
`[!] ${timestamp}\n`,
...messages,
);
}

/**
* Create a helper to merge base URL and path.
* @param {string} baseUrl - The base URL
* @return {function(string)}
*/
function urlGlue(baseUrl) {
return (path) => baseUrl + path;
}

/**
* Return a function to run a task with arguments.
* @param {function} task
* @return {any}
*/
function toTest(task, ...args) {
return async function() {
try {
await task(...args);
} catch (error) {
console.error(error);
throw error;
}
};
}

/**
* Run prepare handlers.
* @return {object}
* @param {function[]} handlers
* @return {function}
*/
async function runPrepareHandlers(...prepareHandlers) {
// Waiting for prepare handlers
if (prepareHandlers.length > 0) {
const preparingPromises = prepareHandlers.map((c) => c());
await Promise.all(preparingPromises);
}
function toPrepare(...handlers) {
return async function() {
try {
const promises = handlers.map((c) => c());
await Promise.all(promises);
} catch (error) {
console.error(error);
throw error;
}
};
}

/**
* Generate fake user of the testing session.
* @return {object}
*/
function generateFakeUser() {
const sessionCode = `testing_${generateNanoId()}`;
const userSerial = generateNanoId();
const userId = `testing_${userSerial}`;

return {
nickname: `Sara Hoshikawa - ${sessionCode}`,
email: `sara_${sessionCode}@web-tech-tw.github.io`,
};
const nickname = `Sara Hoshikawa - ${userId}`;
const email = `sara_${userId}@web-tech-tw.github.io`;

return {nickname, email};
}

/**
Expand All @@ -46,45 +92,32 @@ async function registerFakeUser(userData) {

const verifyResponse = await request(app).
post("/users").
send(userData).
type("json").
expect(StatusCodes.CREATED);
send(userData).
expect(StatusCodes.CREATED).
expect("Content-Type", /json/);

const {session_id: sessionId} = verifyResponse.body;
const sessionCode = cache.take("_testing_code");

const {session_id: sessionCode} = verifyResponse.body;
const statusResponse = await request(app).
patch("/users").
type("json").
send({
session_id: sessionCode,
code: cache.take("_testing_code"),
session_id: sessionId,
code: sessionCode,
}).
type("json").
expect(StatusCodes.CREATED);
expect(StatusCodes.CREATED).
expect("Content-Type", /plain/);

return statusResponse.status === StatusCodes.CREATED;
}

/**
* Print message with testing notification.
* @param {any} messages
*/
function log(...messages) {
if (isProduction()) return;
console.info("[!] Test mode:", ...messages);
}

/**
* Create a helper to merge base URL and path.
* @param {string} baseUrl - The base URL
* @return {function(string)}
*/
function urlGlue(baseUrl) {
return (path) => baseUrl + path;
}

module.exports = {
runPrepareHandlers,
print,
urlGlue,
toTest,
toPrepare,
generateFakeUser,
registerFakeUser,
log,
urlGlue,
};
84 changes: 45 additions & 39 deletions test/tokens.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@

require("./kernel/init");

const utils = require("./kernel/utils");
const {
print,
urlGlue,
toTest,
toPrepare,
generateFakeUser,
registerFakeUser,
} = require("./kernel/utils");

const request = require("supertest");
const {step} = require("mocha-steps");
Expand All @@ -25,55 +32,54 @@ const app = useApp();
const cache = useCache();

const routerDispatcher = require("../src/routes/index");
const to = utils.urlGlue("/tokens");
const to = urlGlue("/tokens");
routerDispatcher.load();

// Define tests
describe("/tokens", function() {
const fakeUser = utils.generateFakeUser();
const fakeUser = generateFakeUser();
const fakeUserRegister = () => registerFakeUser(fakeUser);

before(async () => {
await utils.runPrepareHandlers(
prepareDatabase,
);
await utils.registerFakeUser(fakeUser);
});
before(toPrepare(
prepareDatabase,
fakeUserRegister,
));

step("login", function(done) {
request(app).
step("login", toTest(async function() {
const response = await request(app).
post(to("/")).
send({email: fakeUser.email}).
type("json").
set("Accept", "application/json").
send({email: fakeUser.email}).
expect(StatusCodes.CREATED).
then((res) => {
cache.set("_testing_session_id", res.body.session_id);
done();
}).
catch((e) => {
console.error(e);
done(e);
});
});

step("login verify", function(done) {
request(app).
expect("Content-Type", /json/);

const {
session_id: sessionId,
} = response.body;

cache.set("_testing_session_id", sessionId);

print(response.body);
}));

step("login verify", toTest(async function() {
const code = cache.take("_testing_code");
const sessionId = cache.take("_testing_session_id");

const response = await request(app).
patch(to("/")).
type("json").
send({
session_id: cache.take("_testing_session_id"),
code: cache.take("_testing_code"),
code: code,
session_id: sessionId,
}).
type("json").
set("Accept", "text/plain").
expect("Content-Type", /plain/).
expect(StatusCodes.CREATED).
then((res) => {
utils.log(headerRefreshToken, res.headers[headerRefreshToken]);
done();
}).
catch((e) => {
console.error(e);
done(e);
});
});
expect("Content-Type", /plain/);

const {
[headerRefreshToken]: refreshToken,
} = response.headers;

print(refreshToken);
}));
});
79 changes: 42 additions & 37 deletions test/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@

require("./kernel/init");

const utils = require("./kernel/utils");
const {
print,
urlGlue,
toTest,
toPrepare,
generateFakeUser,
} = require("./kernel/utils");

const request = require("supertest");
const {step} = require("mocha-steps");
Expand All @@ -25,53 +31,52 @@ const app = useApp();
const cache = useCache();

const routerDispatcher = require("../src/routes/index");
const to = utils.urlGlue("/users");
const to = urlGlue("/users");
routerDispatcher.load();

// Define tests
describe("/users", function() {
const fakeUser = utils.generateFakeUser();
const fakeUser = generateFakeUser();

before(async () => {
await utils.runPrepareHandlers(
prepareDatabase,
);
});
before(toPrepare(
prepareDatabase,
));

step("register", function(done) {
request(app).
step("register", toTest(async function() {
const response = await request(app).
post(to("/")).
send(fakeUser).
type("json").
set("Accept", "application/json").
send(fakeUser).
expect(StatusCodes.CREATED).
then((res) => {
cache.set("_testing_session_id", res.body.session_id);
utils.log(res.body);
done();
}).
catch((e) => {
utils.log(e);
done(e);
});
});

step("verify register", function(done) {
request(app).
expect("Content-Type", /json/);

const {
session_id: sessionId,
} = response.body;

cache.set("_testing_session_id", sessionId);

print(response.body);
}));

step("verify register", toTest(async function() {
const code = cache.take("_testing_code");
const sessionId = cache.take("_testing_session_id");

const response = await request(app).
patch(to("/")).
type("json").
send({
session_id: cache.take("_testing_session_id"),
code: cache.take("_testing_code"),
code: code,
session_id: sessionId,
}).
type("json").
expect(StatusCodes.CREATED).
then((res) => {
utils.log(headerRefreshToken, res.headers[headerRefreshToken]);
done();
}).
catch((e) => {
utils.log(e);
done(e);
});
});
expect("Content-Type", /plain/);

const {
[headerRefreshToken]: refreshToken,
} = response.headers;

print(refreshToken);
}));
});

0 comments on commit af3b7dc

Please sign in to comment.