ip2region/binding/nodejs/tests/constructorTest.spec.js
MaleDong 35fc3cbf23 Refactor of codes in node.js
1) Add async method: `binarySearch` and `btreeSearch`.
2) Refactor of tests by putting them into `tests` folder.
3) Create several new tests in details.
4) Remove useless and reformat codes to be clear.
5) Remove useless snapshots, because they can be recreated when you run `npm run test`.
2018-07-29 20:02:14 +08:00

109 lines
2.5 KiB
JavaScript

// This test is used for tesing of a static function `create` of IP2Region
const IP2Region = require('../ip2region');
const testIps = require('./utils/testData');
const asyncFor = require('./utils/asyncFor');
describe('Constructor Test', () => {
let instance;
beforeAll(() => {
instance = new IP2Region({ dbPath: '../../data/ip2region.db' });
});
afterAll(() => {
IP2Region.destroy();
});
test('btreeSearchSync query', () => {
for (const ip of testIps) {
expect(instance.btreeSearchSync(ip)).toMatchSnapshot();
}
});
test('binarySearchSync query', () => {
for (const ip of testIps) {
expect(instance.binarySearchSync(ip)).toMatchSnapshot();
}
});
//#region callBack
test('binarySearch query', (done) => {
asyncFor(testIps,
(value, continueCallBack) => {
instance.binarySearch(value, (err, result) => {
expect(err).toBe(null);
expect(result).toMatchSnapshot();
continueCallBack();
});
},
() => { done() });
});
test('btreeSearch query', (done) => {
asyncFor(testIps,
(value, continueCallBack) => {
instance.btreeSearch(value, (err, result) => {
expect(err).toBe(null);
expect(result).toMatchSnapshot();
continueCallBack();
});
},
() => { done() });
});
//#endregion
//#region Async Promisify test
const node_ver = require('./utils/fetchMainVersion');
// If we have Nodejs >= 8, we now support `async` and `await`
if (node_ver >= 8) {
const asyncBinarySearch = async (ip) => {
return new Promise((resolve, reject) => {
instance.binarySearch(ip, (err, result) => {
if (err) {
reject(err);
}
else {
resolve(result);
}
});
});
};
const asyncBtreeSearch = async (ip) => {
return new Promise((resolve, reject) => {
instance.btreeSearch(ip, (err, result) => {
if (err) {
reject(err);
}
else {
resolve(result);
}
});
});
};
test('async binarySearch query', async () => {
for (let i = 0; i < testIps.length; ++i) {
const result = await asyncBinarySearch(testIps[i]);
expect(result).toMatchSnapshot();
}
});
test('async btreeSearch query', async () => {
for (let i = 0; i < testIps.length; ++i) {
const result = await asyncBtreeSearch(testIps[i]);
expect(result).toMatchSnapshot();
}
});
}
//#endregion
});