Skip to content

Commit

Permalink
build: add some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Jul 10, 2019
1 parent b8f515b commit 47803a6
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 16 deletions.
1 change: 1 addition & 0 deletions packages/metascraper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
"cheerio-advanced-selectors": "~2.0.1",
"has-values": "~2.0.1",
"lodash": "~4.17.13",
"map-values-deep": "~1.0.1",
"whoops": "~4.0.2",
"xss": "~1.0.6"
},
Expand Down
28 changes: 12 additions & 16 deletions packages/metascraper/src/get-data.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,34 @@
'use strict'

const { map, fromPairs, isObject, isArray, mapValues } = require('lodash')
const has = require('has-values')
const { isNil, map, fromPairs } = require('lodash')
const mapValuesDeep = require('map-values-deep')
const hasValues = require('has-values')

const xss = require('xss')

const has = value =>
isNil(value) || value === false || value === 0 || value === ''
? false
: hasValues(value)

const noopTest = () => true

const getValue = async ({ htmlDom, url, rules, meta }) => {
const lastIndex = rules.length
let index = 0
let value

while (!has(value) && index < lastIndex) {
do {
const rule = rules[index++]
const test = rule.test || noopTest
if (test({ htmlDom, url, meta })) {
value = await rule({ htmlDom, url, meta })
}
}
} while (!has(value) && index < lastIndex)

return value
}

const mapValuesDeep = (object, fn) => {
if (isArray(object)) {
return map(object, innerObject => mapValuesDeep(innerObject, fn))
}

if (isObject(object)) {
return mapValues(object, value => mapValuesDeep(value, fn))
}

return fn(object)
}

const escapeValue = (value, { escape }) =>
!escape ? value : mapValuesDeep(value, xss)

Expand All @@ -50,3 +45,4 @@ const getData = async ({ rules, htmlDom, url, escape }) => {
}

module.exports = getData
module.exports.has = has
26 changes: 26 additions & 0 deletions packages/metascraper/test/unit/get-data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict'

const should = require('should')

const { has } = require('../../src/get-data')

describe('.has', () => {
it('true', () => {
should(has(true)).be.true()
should(has('foo')).be.true()
should(has(123)).be.true()
should(has(['foo'])).be.true()
should(has({ foo: 'bar' })).be.true()
})

it('false', () => {
should(has(false)).be.false()
should(has(0)).be.false()
should(has('')).be.false()
should(has(null)).be.false()
should(has(undefined)).be.false()
should(has({})).be.false()
should(has([])).be.false()
should(has([''])).be.false()
})
})

0 comments on commit 47803a6

Please sign in to comment.