Skip to content

Commit

Permalink
test(coverage): improve test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
JaredReisinger committed Jul 19, 2024
1 parent b1bfcb0 commit 1bdb6bf
Show file tree
Hide file tree
Showing 8 changed files with 127 additions and 87 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"plainjs",
"plusplus",
"scrollback",
"skus",
"snyk",
"tseslint",
"tsimp",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"clean": "rm -r .tsimp coverage dist",
"lint": "eslint ./src",
"test": "ava",
"test:coverage": "c8 --all --src src --per-file --reporter lcov --reporter text npm test",
"test:coverage": "c8 --all --src src --exclude 'src/stub.ts' --exclude 'src/wc/woocommerce-types.ts' --per-file --reporter lcov --reporter text npm test",
"coverage": "npm run test:coverage",
"codecov": "codecov",
"commit": "git-cz",
Expand Down
2 changes: 1 addition & 1 deletion src/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ test.afterEach(() => {
process.argv = prevArgs;
});

test('cli... runs the app', async (t) => {
test('cli main runs the app', async (t) => {
process.argv = ['', '', '--help'];
await t.notThrowsAsync(() => main(preventYargsExit));
});
68 changes: 52 additions & 16 deletions src/commands/get.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import moment from 'moment-timezone';
import WooClient from '../wc/WooClient.js';
import WooItem from '../wc/WooItem.js';
import WooCurrencies from '../wc/WooCurrencies.js';
// import { Order } from '../wc/woocommerce-types.js';

import Get from './get.js';

Expand All @@ -24,26 +25,42 @@ const currencies = [
];

const order = {
id: '12345',
id: 12345,
number: '12345',
date_created_gmt: '2000-01-01T12:00:00.000Z',
status: 'STATUS',
total: '123.45',
currency: 'usd',
billing: {},
billing: {
first_name: 'FIRST_NAME',
last_name: 'LAST_NAME',
company: 'COMPANY',
address_1: 'ADDRESS_1',
address_2: 'ADDRESS_2',
city: 'CITY',
state: 'STATE',
postcode: 'POSTCODE',
country: 'COUNTRY',
email: 'EMAIL',
phone: 'PHONE',
},
line_items: [
{
id: '123',
id: 123,
name: 'ITEM_NAME_1',
sku: 'SKU_1',
total: '1.23',
},
{
id: '234',
id: 234,
name: 'ITEM_NAME_2',
sku: 'SKU_2',
total: '2.34',
meta_data: [
{ value: 'missing key' },
{ key: '_ignored', value: 'WooCommerce-style metadata' },
// { key: 'v1 price $0.99', value: 'v1-style price-included key' },
{ key: 'phone', value: '8005551212' },
{ key: 'meta-phone', value: '800-555-1212' },
],
},
],
Expand All @@ -65,17 +82,6 @@ function createGet() {
);
}

// async function runCommand(...args) {
// process.argv = [
// "node", // Not used but a value is required at this index in the array
// "cli.js", // Not used but a value is required at this index in the array
// ...args,
// ];

// // Require the yargs CLI script
// return require("./cli");
// }

test('Get.createCommands() should return a Promise', async (t) => {
const get = createGet();
const result = get.createCommands();
Expand Down Expand Up @@ -346,4 +352,34 @@ test('Get.run() can present specific columns', async (t) => {
await t.notThrowsAsync(result);
});

test('Get.run() can output CSV to a file', async (t) => {
const get = createGet();
const { client, stub } = createClientStub();

stub.withArgs('data/currencies').resolves(currencies);
stub.withArgs('orders').resolves([order]);

const writeFile = sinon.stub(get, 'writeFile').resolves();

const result = get.run(
'foo',
// @ts-expect-error -- fake args
{ out: 'BOGUS.csv' },
client
);

await t.notThrowsAsync(result);

t.is(writeFile.callCount, 1);
t.deepEqual(writeFile.getCall(0).args, [
'BOGUS.csv',
// don't forget leading BOM!
`\uFEFF"order#","date","status","name","email","address","phone","sku","item","qty","total","fees","method","transID","note","meta-phone"
12345,"1/1/2000 12:00:00 PM","STATUS","FIRST_NAME LAST_NAME","EMAIL","ADDRESS_1, ADDRESS_2, CITY, STATE POSTCODE","PHONE","SKU_1","ITEM_NAME_1",,"$1.23",,,,,
12345,"1/1/2000 12:00:00 PM","STATUS","FIRST_NAME LAST_NAME","EMAIL","ADDRESS_1, ADDRESS_2, CITY, STATE POSTCODE","PHONE","SKU_2","ITEM_NAME_2",,"$2.34",,,,,"800-555-1212"`,
]);

writeFile.restore();
});

// TODO: test after/before/status filtering (in call!)
72 changes: 25 additions & 47 deletions src/commands/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,8 @@ export default class Get {
// handler: a function which will be passed the parsed argv.
async createCommand(host?: string): Promise<CommandModule<Args, Args>> {
const command = host || 'get';
// const aliases = '*'; // this is the default command
const aliases = undefined;
const describe = `gets orders from ${
host ? `the ${host}` : 'a'
} WooCommerce site`;
const describe = `gets orders from ${host ? `the ${host}` : 'a'} WooCommerce site`;

const builder: CommandBuilder<Args, Args> = (yargs) => {
if (!host) {
Expand Down Expand Up @@ -220,24 +217,24 @@ export default class Get {
// describe: 'Whether to verify the SSL certificate from the host',
// boolean: true,
// })
// .group(['after', 'before', 'status'], 'Order Filtering')
// .group(['sku', 'sku-prefix'], 'Item Filtering')
// .group(
// [
// 'omit-blanks',
// 'omit-identical',
// 'omit-payment',
// 'omit',
// 'include',
// 'columns',
// ],
// 'Column Filtering'
// )
// .group(['out'], 'Output')
// .group(
// ['list-skus', 'list-statuses', 'list-columns'],
// 'Discovery (incompatible with "--out" option)'
// )
.group(['after', 'before', 'status'], 'Order Filtering')
.group(['sku', 'sku-prefix'], 'Item Filtering')
.group(
[
'omit-blanks',
'omit-identical',
'omit-payment',
'omit',
'include',
'columns',
],
'Column Filtering'
)
.group(['out'], 'Output')
.group(
['list-skus', 'list-statuses', 'list-columns'],
'Discovery (incompatible with "--out" option)'
)
.epilogue(
`--------------------------------------------------------------------------------
Best Practices:
Expand Down Expand Up @@ -277,20 +274,6 @@ Examples:
};
}

// if (hosts.length !== 0) {
// console.log(chalkTemplate`{red Creating the config file:
//
// You do not appear to have any hosts listed in a {cyan ~/.${pkgInfo.name}.json}
// file. Please see:
// {cyan.underline ${pkgInfo.homepage}}
// for instructions onsetting this up.}
// `);
// }
// })
// // .action(this.handleGlobalOpts)
// .action(this.run);
// }

async run(
seededHost: string | undefined,
argv: ArgumentsCamelCase<Args>,
Expand Down Expand Up @@ -325,16 +308,7 @@ Examples:
}

const client =
clientOverride ??
new WooClient(
host.url,
host.key,
host.secret /*, {
verifySsl: argv.verifySsl,
}*/
);

// new order stuff...
clientOverride ?? new WooClient(host.url, host.key, host.secret);

// Get orders/items and the currencies in parallel. We could delay awaiting
// on the currencies until just before generating the CSV, but the code is a
Expand Down Expand Up @@ -430,7 +404,7 @@ Examples:
}
if (argv.out) {
const csv = this.generateCsv(items, fields);
await writeFileAsync(argv.out, csv);
await this.writeFile(argv.out, csv);
} else {
const display = this.generatePretty(items, fields);
helpers.out('');
Expand All @@ -445,6 +419,10 @@ Examples:
return csv;
}

async writeFile(filename: string, content: string) {
await writeFileAsync(filename, content);
}

generatePretty(items: WooItem[], fields: AugmentedFieldInfo<WooItem>[]) {
// colorize the date field, for fun...
fields.forEach((f) => {
Expand Down
4 changes: 4 additions & 0 deletions src/stub.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
#!/usr/bin/env node
/* c8 ignore start */
import process from 'node:process';

import chalk from 'chalk';

import { err, UserError } from './helpers.js';
Expand All @@ -19,3 +22,4 @@ try {

process.exit(1);
}
/* c8 ignore end */
13 changes: 10 additions & 3 deletions src/wc/WooClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,21 @@ import test from 'ava';

import WooClient, { percentEncode } from './WooClient.js';

test('WooClient constructor should create an object', (t) => {
const result = new WooClient('URL', 'KEY', 'SECRET');
test('WooClient constructor creates an object with HTTPS', (t) => {
const result = new WooClient('https://URL.org', 'KEY', 'SECRET');
t.true(result instanceof Object);
t.true('_apiVersion' in result);
t.true('_ky' in result);
});

test.only('percentEncode()', (t) => {
test('WooClient constructor creates an object with HTTP', (t) => {
const result = new WooClient('http://URL.org', 'KEY', 'SECRET');
t.true(result instanceof Object);
t.true('_apiVersion' in result);
t.true('_ky' in result);
});

test('percentEncode()', (t) => {
const cases: [string, string][] = [
['a', 'a'],
['z', 'z'],
Expand Down
52 changes: 33 additions & 19 deletions src/wc/wcutils.test.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
import test from 'ava';
import * as wcutils from './wcutils.js';

test('wcutils normalizePhone() should convert special "no value" sentinels to "(none)"', (t) => {
t.is(wcutils.normalizePhone('none'), '(none)');
t.is(wcutils.normalizePhone('na'), '(none)');
t.is(wcutils.normalizePhone('n/a'), '(none)');
t.is(wcutils.normalizePhone('no fax'), '(none)');
t.is(wcutils.normalizePhone('x'), '(none)');
t.is(wcutils.normalizePhone('xx'), '(none)');
t.is(wcutils.normalizePhone('xxx'), '(none)');
t.is(wcutils.normalizePhone(''), '(none)');
t.is(wcutils.normalizePhone(' '), '(none)');
t.is(wcutils.normalizePhone(' '), '(none)');
});

test('wcutils normalizePhone() should remove non-numeric characters for standard lengths', (t) => {
t.is(wcutils.normalizePhone('123abc4567'), '123-4567');
t.is(wcutils.normalizePhone('123abc4567xyz890'), '(123) 456-7890');
});
test('wcutils normalizePhone()', (t) => {
const cases: [string, string][] = [
// standard lengths/formatting
['1234567', '123-4567'],
['1234567890', '(123) 456-7890'],
['11234567890', '(123) 456-7890'],
// weird 9-digit cases..
['123456789', '(123) 45?-6789'],
// weird 11-to-14-digit (not leading 1) cases...
['92345678901', '(923) 456-7890 (+1)'],
['923456789012', '(923) 456-7890 (+12)'],
['9234567890123', '(923) 456-7890 (+123)'],
['92345678901234', '(923) 456-7890 (+1234)'],
// "no value" sentinels
['none', '(none)'],
['na', '(none)'],
['n/a', '(none)'],
['no fax', '(none)'],
['x', '(none)'],
['xx', '(none)'],
['xxx', '(none)'],
['', '(none)'],
[' ', '(none)'],
[' ', '(none)'],
// non-numeric
['123abc4567', '123-4567'],
['123abc4567xyz890', '(123) 456-7890'],
// unrecognized lengths
['123abc', '123abc'],
];

test('wcutils normalizePhone() should leave untouched for unrecognized lengths', (t) => {
t.is(wcutils.normalizePhone('123abc'), '123abc');
cases.forEach(([input, expected], i) => {
t.is(wcutils.normalizePhone(input), expected, `case ${i} "${input}"`);
});
});

0 comments on commit 1bdb6bf

Please sign in to comment.