otp-wallet-cli
Version:
OTP Wallet CLI
88 lines (78 loc) • 2.29 kB
JavaScript
// Import.
import fs from 'fs';
import path from 'path';
import { DATA_FILE_PATH, loadData, saveData, addApp, deleteApp } from './app';
/**
* Before each test, delete the data file if it exists.
*/
beforeEach(() => {
if (fs.existsSync(DATA_FILE_PATH)) {
fs.unlinkSync(DATA_FILE_PATH);
}
process.env.USERPROFILE = path.dirname(DATA_FILE_PATH);
});
/**
* After all tests, delete the data file if it exists.
*/
afterAll(() => {
if (fs.existsSync(DATA_FILE_PATH)) {
fs.unlinkSync(DATA_FILE_PATH);
}
});
/**
* Tests that the data file is created if it does not exist.
*/
describe('loadData', () => {
test('should return an empty array if file does not exist', () => {
expect(loadData()).toEqual([]);
});
test('should return data from file if it exists', () => {
const sampleData = [{ name: 'App1', secret: 'SECRET1' }];
fs.writeFileSync(DATA_FILE_PATH, JSON.stringify(sampleData));
expect(loadData()).toEqual(sampleData);
});
});
/**
* Tests that the data is written to the file.
*/
describe('saveData', () => {
test('should write data to file', () => {
const sampleData = [{ name: 'App1', secret: 'SECRET1' }];
saveData(sampleData);
const fileData = JSON.parse(fs.readFileSync(DATA_FILE_PATH, 'utf-8'));
expect(fileData).toEqual(sampleData);
});
});
/**
* Tests that the OTP codes are loaded and correctly.
*/
describe('addApp', () => {
test('should add a new app to data file', () => {
addApp('App1', 'SECRET1');
const data = loadData();
expect(data).toEqual([{ name: 'App1', secret: 'SECRET1' }]);
});
test('should not add an app if it already exists', () => {
addApp('App1', 'SECRET1');
addApp('App1', 'SECRET1');
const data = loadData();
expect(data).toEqual([{ name: 'App1', secret: 'SECRET1' }]);
});
});
/**
* Tests that the app is deleted correctly.
*/
describe('deleteApp', () => {
test('should delete an existing app', () => {
addApp('App1', 'SECRET1');
deleteApp('App1');
const data = loadData();
expect(data).toEqual([]);
});
test('should do nothing if app does not exist', () => {
addApp('App1', 'SECRET1');
deleteApp('App2');
const data = loadData();
expect(data).toEqual([{ name: 'App1', secret: 'SECRET1' }]);
});
});