Unit testing comes to TMS WEB Core
Introducing unit testing now integrated from TMS WEB Core v1.9.5.0.
To start a new unit test project, create this from the Delphi IDE wizard and it creates a test project with one unit containing one test class with one test method. It allows you to fully focus on writing the test classes with their test methods.
Notice in the code the attribute [TestFixture] on the test classes and the attribute [Test] on the test methods. A class can obviously contain as much test methods as you want and you can register as much test classes as you want with a call to TTMSWEBUnitTestingRunner.RegisterClass(). For the feedback when running the test application, use the Assert class.
When running this application, the test application in the browser behaves in the following way:
Asynchronous behavior in the browser
Now, how can we deal with typical asynchronous behavior in the browser and still test it properly? Well, for any asynchronous behavior in the browser, decorate the test method using it with the [Async] attribute. Then you can use the await() function to wait for the asynchronous response of the call. This sample code demonstrates this:
TMyTestClassUnit1 = class(TObject) published //This is an async test method [Test] [async] procedure TestAsync; end; procedure TMyTestClassUnit1.TestAsync; var wr: TWebHttpRequest; res: TJSXMLHttpRequest; js: TJSONObject; begin wr := TWebHttpRequest.Create(nil); wr.URL := 'https://download.tmssoftware.com/tmsweb/1.json'; res := await(TJSXMLHttpRequest, wr.Perform); js := TJSONObject(TJSONObject.ParseJSONValue(res.responseText)); // response value for userId should be '1' Assert.AreEqual(js.GetJSONValue('userId'),'1'); end;
Testing JavaScript directly
When you use external JavaScript libraries that you also want to involve in a test, there are several ways you can do this. You might have an Object Pascal wrapper class for JavaScript objects that you use in your test method but it could be as simple as calling the JavaScript directly from an ASM code block (a block with embedded JavaScript code within your Object Pascal code).
This is a very simple example of directly calling the JavaScript window prompt function to get a user input:
procedure TMyTestClassUnit2.TestIntToStr; var s: string; begin asm s = window.prompt('Please give your name'); end; Assert.AreEqual('Bruno', s); end;
A video introduction
Follow unit testing step by step as our colleague Holger Flick explains in this YouTube video: