Javascript – test effectively javascript functions with a PHP unit-testing framework

javascriptPHPunit testing

If I want to unit-test some of my javascript functions, would it be more efficient (and doable) to use the already installed PHP unit-testing framework, or should I use a javascript unit-testing framework?

EDIT: It seems I have to clarify things a bit. I'm using javascript for form validation. It seems that some logic doesn't work as I want it to be, and I thought to myself that would be a good point to begin to use unit-testing (something that came to my scope only recently). I already began to use SimpleTest on a little project of mine, but never to test logic that is generated client-side.

Now I know that SimpleTest have the possibility to emulate a browser for example. But I was wondering what other method would they be to unit-test my form validation. While I was searching for idea, I realized that there is also unit-testing framework for javascript, but after a bit of searching on some of the SE sites, I didn't find anything about use of PHP and Javascript Framework together, so I wondered how common such a situation it was, and how do other people manage in such an environment.

Best Answer

The short answer is no.

You cannot effectively test JavaScript with PHP. To do it effectively, you need to use JavaScript.

More than likely you will have to use a JavaScript unit testing library such as the one used for Prototype.js. Essentially, you need to be able to execute the JavaScript in browser, and get the results of the JavaScript run. You won't be able to do that from the server side (PHP).

Unit testing frameworks are most efficient and useful when you are using the same language to test as you are to write the code in. For that reason we have PHP unit testing frameworks, Java unit testing frameworks, C#/.Net unit testing frameworks, and yes, JavaScript unit testing frameworks. A big part of the reason for this is that your unit tests need to examine the results of what your code is doing in the environment where it runs. SimpleTest runs in the PHP environment, and examines to assert that your PHP functions are doing what you expect. It doesn't run directly in the client browser, but as all PHP code it runs on the server and generates HTML output.

In order to run and test JavaScript functionality--particularly when the problem might be how a one browser implements it--you need to execute and assert functionality in JavaScript. Now, you can roll your own JavaScript unit testing framework for your environment, or you can use one that already exists.

The JavaScript lives 100% on the client side. That's why you didn't see anything about running JavaScript and PHP together--just as you won't find information on Java and JavaScript together (in the same context we are talking here).

Related Topic