avocado/packages/code/test/function.js
2022-04-05 13:23:17 -05:00

97 lines
2.8 KiB
JavaScript

import generate from '@babel/generator';
import {
identifier,
numericLiteral,
} from '@babel/types';
import {expect} from 'chai';
import {
extractExpressionFromFunction,
extractFunction,
hasExternalDependency,
rewriteParams,
} from '../src/function';
import parse from '../src/parse';
it('can extract functions', () => {
expect(extractFunction(parse('() => {}')))
.to.not.be.undefined;
expect(extractFunction(parse('function test() {}')))
.to.not.be.undefined;
});
it('can extract expressions from functions', () => {
const {type, value} = extractExpressionFromFunction(extractFunction(parse('() => 69')));
expect({type, value})
.to.deep.equal({type: 'NumericLiteral', value: 69});
expect(extractExpressionFromFunction(extractFunction(parse('() => a + b'))).type)
.to.equal('BinaryExpression');
expect(extractExpressionFromFunction(extractFunction(parse(
'function anon() { return this.whatever; }',
))))
.to.not.be.undefined;
});
it('can identify external dependencies', () => {
expect(hasExternalDependency(
extractFunction(parse('function test(a, b) { const c = a; }')),
))
.to.be.false;
expect(hasExternalDependency(
extractFunction(parse('function test(a, b) { const c = d; }')),
))
.to.be.true;
expect(hasExternalDependency(
extractFunction(parse('function test(a, b) { c.a.b; }')),
))
.to.be.true;
expect(hasExternalDependency(
extractFunction(parse('function test(a, b) { c.d; }')),
))
.to.be.true;
expect(hasExternalDependency(
extractFunction(parse('function test(a, b) { Math.min(a, b); }')),
))
.to.be.false;
expect(hasExternalDependency(
extractFunction(parse('function test(a, b) { super.whatever; }', {allowSuperOutsideMethod: true})),
))
.to.be.true;
expect(hasExternalDependency(
extractFunction(parse('function test(a, b) { this.whatever; }')),
))
.to.be.false;
expect(hasExternalDependency(
extractFunction(parse('function test(a, b) { this.foo.whatever }')),
))
.to.be.false;
expect(hasExternalDependency(
extractFunction(parse('function test(a, b) { console.log("HI"); }')),
))
.to.be.true;
expect(hasExternalDependency(
extractFunction(parse('function test(a, b) { const [c, d] = a; }')),
))
.to.be.false;
});
it('can rewrite parameters', () => {
const ast = extractFunction(parse('function test(a, b) { return a + b; }'));
rewriteParams(ast, [identifier('test'), numericLiteral(69)]);
expect(generate(ast.body, {concise: true}).code)
.to.equal('{ return test + 69; }');
const ast2 = extractFunction(parse('function test(a, b) { return a[0] + b[0]; }'));
rewriteParams(ast2, [identifier('test'), identifier('test2')]);
expect(generate(ast2.body, {concise: true}).code)
.to.equal('{ return test[0] + test2[0]; }');
});