Unit tests for Screeps snippets
-
Hey,
I'm kinda new to the whole JavaScript shenanigans, but I'm quite experienced with various languages.
I'm used to, and would prefer, writing unit tests for my code, before writing the actual code. I have set up Mocha, and it seems to be working correctly. My issue is now that I can't test code that uses any Screeps function, since those are hidden away.
I've never had to write tests for code outside of the environment, so to say. Is it possible to somehow work around this?I've made a function,
RoomPosition.prototype.getAdjacent = function(direction) { ... }
Which takes a direction and returns the adjacent position in that direction. Now my issue is that I can't test this.
It seems logical to do something like this:
var assert = require('chai').assert;
require('../../src/prototypes/prototype.RoomPosition')();
describe('RoomPosition', function() {
describe('#getAdjacent(direction)', function() {
it('should return a new RoomPosition moved in the direction', function() {
var pos = new RoomPosition(1, 1, 'TestingRoom');
assert.equal(pos.getAdjacent(TOP), new RoomPosition(1, 0, 'TestingRoom'));
});
});
});But, then I'd need to be able to somehow inject the constructor for RoomPosition, and also the values for the direction constants.
Any help would be appreciated!
-
I successfully solved this. I have a github repo where you can see how.
-
Thanks for posting your solution. I'm also going to cover my codebase with unit tests before it grows out of control, your solution is a good starting point for me, although I believe it's not the best way to go long-term wise. All this global environment looks like a pain to test with. I think what we can do instead is having every module each piece it depends on during the construction instead of letting it blindly using global environment in it's methods. Should dig more into this. Just thinking out loud.
I guess it was a pain to compose the game state mock (https://github.com/Jomik/screeps/blob/master/lib/mocks/mockGameState.js) wasn't it... Did you go over the API and manually picked the constants / objects / functions from there?
Thanks for posting this. I think you're among the first explorers of unit testing in screeps, if not the first one