Add test coverage

Also extracted some functions from index.js.