napi-rs/examples/napi/__test__/values.spec.ts

133 lines
2.7 KiB
TypeScript
Raw Normal View History

2021-10-25 01:00:31 +09:00
import { join } from 'path'
import test from 'ava'
import {
add,
fibonacci,
contains,
concatLatin1,
concatStr,
concatUtf16,
getNums,
getWords,
sumNums,
getCwd,
Animal,
Kind,
CustomNumEnum,
enumToI32,
listObjKeys,
createObj,
mapOption,
2021-09-24 10:15:48 +09:00
readFile,
throwError,
2021-09-24 18:01:54 +09:00
readPackageJson,
2021-09-28 01:01:19 +09:00
getPackageJsonName,
2021-10-08 22:13:27 +09:00
getBuffer,
2021-10-25 01:00:31 +09:00
readFileAsync,
} from '../'
test('number', (t) => {
t.is(add(1, 2), 3)
t.is(fibonacci(5), 5)
t.throws(
// @ts-expect-error
() => fibonacci(''),
null,
'Expect value to be Number, but received String',
)
})
test('string', (t) => {
t.true(contains('hello', 'ell'))
t.false(contains('John', 'jn'))
t.is(concatStr('涽¾DEL'), '涽¾DEL + Rust 🦀 string!')
t.is(concatLatin1('涽¾DEL'), '涽¾DEL + Rust 🦀 string!')
t.is(
concatUtf16('JavaScript 🌳 你好 napi'),
'JavaScript 🌳 你好 napi + Rust 🦀 string!',
)
})
test('array', (t) => {
t.deepEqual(getNums(), [1, 1, 2, 3, 5, 8])
t.deepEqual(getWords(), ['foo', 'bar'])
t.is(sumNums([1, 2, 3, 4, 5]), 15)
})
test('enum', (t) => {
t.deepEqual([Kind.Dog, Kind.Cat, Kind.Duck], [0, 1, 2])
t.is(enumToI32(CustomNumEnum.Eight), 8)
})
test('class', (t) => {
const dog = new Animal(Kind.Dog, '旺财')
t.is(dog.name, '旺财')
t.is(dog.kind, Kind.Dog)
t.is(dog.whoami(), 'Dog: 旺财')
dog.name = '可乐'
t.is(dog.name, '可乐')
})
test('callback', (t) => {
getCwd((cwd) => {
t.is(cwd, process.cwd())
})
t.throws(
// @ts-expect-error
() => getCwd(),
null,
'Expect value to be Function, but received Undefined',
)
2021-09-24 10:15:48 +09:00
readFile((err, content) => {
2021-09-24 10:46:27 +09:00
t.is(err, undefined)
2021-09-24 10:15:48 +09:00
t.is(content, 'hello world')
})
})
test('object', (t) => {
t.deepEqual(listObjKeys({ name: 'John Doe', age: 20 }), ['name', 'age'])
t.deepEqual(createObj(), { test: 1 })
})
test('Option', (t) => {
2021-09-24 10:46:27 +09:00
t.is(mapOption(null), null)
t.is(mapOption(3), 4)
})
2021-09-24 10:46:27 +09:00
test('Result', (t) => {
t.throws(() => throwError(), null, 'Manual Error')
2021-09-24 10:46:27 +09:00
})
2021-09-28 01:01:19 +09:00
test('serde-json', (t) => {
const packageJson = readPackageJson()
t.is(packageJson.name, 'napi-rs')
t.is(packageJson.version, '0.0.0')
t.is(packageJson.dependencies, null)
t.snapshot(Object.keys(packageJson.devDependencies!).sort())
t.is(getPackageJsonName(packageJson), 'napi-rs')
})
2021-10-08 22:13:27 +09:00
test('buffer', (t) => {
t.is(getBuffer().toString('utf-8'), 'Hello world')
})
2021-10-25 01:00:31 +09:00
test('async', async (t) => {
const bufPromise = readFileAsync(join(__dirname, '../package.json'))
await t.notThrowsAsync(bufPromise)
const buf = await bufPromise
const { name } = JSON.parse(buf.toString())
t.is(name, 'napi-examples')
await t.throwsAsync(() => readFileAsync('some_nonexist_path.file'))
})