javascriptjunitsapui5qunit

QUnit - Testing functions of files besides formatter.js


The example given by UI5 of testing the formatter functions i.e.

// Assert
assert.strictEqual(fnIsolatedFormatter("A"), "New", "The long text for status A is correct");
assert.strictEqual(fnIsolatedFormatter("B"), "In Progress", "The long text for status B is correct");
assert.strictEqual(fnIsolatedFormatter("C"), "Done", "The long text for status C is correct");
assert.strictEqual(fnIsolatedFormatter("Foo"), "Foo", "The long text for status Foo is correct");

Works out very well, however, the same testing applied to functions of a controller file i.e. Example.controller.js, produces an error.

By trying to test the _onTestFunction of the Example.controller i do get the following error:

TypeError: Example._onTestFunction is not a function

Question: How do i test functions of a controller file that isn't formatter ?


Solution

  • To test a controller, you need to instantiate one: let controllerUnderTest = new Controller(...). If the Controller has any dependencies (as this is usually the case), these dependencies need to be mocked. For this, use a framework such as sinon. Then you can specify in each test how these mocks should behave. Once you have instantiated the controller, you can execute a method and add assertions. In your case, it looks like you are trying to call the _onTestFunction not on an object, but on the "definition" of the Controller. This does not contain the method, as expected, and results in the error.