1

I need help to test my Javascript code. I have a method called update, which will move my enemies for my game around the screen.

constructor(game, x, y, bulletLayer, frame) {
    super(game, x, y, 'enemy', frame);
    this.bounceTick = Math.random() * 2; }

update() {
    this.bounceTick += .02;
    this.y += Math.sin(this.bounceTick) * 1;
} 

When writing my test for it this is what I have attempted to do.

it("moves position correctly", function() {
this.bounceTick = 2;
enemy.update();
assert.equal(Math.sin(this.bounceTick) *1);
 });

This is the error I get- AssertionError: expected NaN to equal undefined.

How would I go about writing a test for the update code to make sure my enemy is moving correctly? I know that I am supposed to set bounceTick to a stationary number since in the class it is being calculated as Math.random() * 2

1 Answer 1

1

The reason for the error message is that you're passing only one argument to assert.equal(Math.sin(this.bounceTick) *1); That function wants two arguments--it's assert.equal, meaning you want it to look at two things and see whether they're equal. The undefined in the error message indicates the missing second argument. The NaN in the message means that your call to Math.sin() is returning a bad value that can't be recognized as a number.

Also, it's going to be hard for you to test this aspect of your code, given that you start bounceTick as a random value. I have written a similar app, with sprites moving around on the screen. I don't test them with a written test as you're doing here; I simply watch them move on the screen and decide whether it looks right.

I don't know of any effective way to test it as you're doing, because the paths your sprites will follow, as well as their starting positions, won't be predictable.

Sign up to request clarification or add additional context in comments.

2 Comments

You can use a javascript mocking library to mock the behavior of Math.random() for the test.
Sounds reasonable, but for my app, I use the physics engine, so my sprites bounce off of each other in unpredictable ways. I guess if OP's sprites are moving on a predefined path, that mock thing could work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.