4

I'm using JsTestDriver and a bit of Jack (only when needed). Does anyone know how to verify that a javascript function has been called during unit testing?

E.g.

function MainFunction()
{
    var someElement = ''; // or = some other type
    anotherFunction(someElement);
}

And in the test code:

Test.prototype.test_mainFunction()
{
    MainFunction();
    // TODO how to verify anotherFunction(someElement) (and its logic) has been called?
}

Thanks.

1 Answer 1

8

JavaScript is very powerful language in terms that you can change the behaviour at runtime.
You can replace anotherFunction with your own during test and verify it has been called:

Test.prototype.test_mainFunction()
{   
    // Arrange 
    var hasBeenCalled = false;
    var old = anotherFunction;
    anotherFunction = function() {
       old();
       hasBeenCalled = true;
    };

    // Act
    MainFunction();

    // Assert (with JsUnit)
    assertEquals("Should be called", true, hasBeenCalled);

    // TearDown
    anotherFunction = old;
}

The note: You should be aware that this test modifies the global function and if it will fail it may not always restore it.
You'd probably better pick JsMock for that.
But in order to use it you need to separate the functions and put them into objects, so you would not have any global data at all.

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

1 Comment

Great answer. I believe there are some JavaScript aspect oriented programming (AOP) libraries to help do this.

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.