0

I need to do unit tests in JEST for a directive in Angular 1.x. Can anybody help me with an example? What I don't know is how I can access the functions from the directive to test them

This is the directive:

angular.module("SEOMod").directive("bfNewToOldTag", [
    "$window",
    "NavigationContext",
    "ROUTE_STATES",
    "$location",
    "BF.SPORT",
    function($window, navigationContext, ROUTE_STATES, $location, bfSport) {
        "use strict";

        let oldURL = navigationContext.view;
        let checkIfNew =  new RegExp("seo");


        function getSportNameEN(id){
            return bfSport.type[id].eventTypeName;
        }

        function getTopDomain() {
            let basePath = "/exchange/plus";
            return $location.protocol() +"://"+ $location.host() + (($location.port() !== 80)?":"+$location.port() : "")+basePath;
        }

       function appendScriptTag() { ...}


        return {
            restrict: "E",
            replace: true,
            controller() {
                appendScriptTag();
            }
        };
    }
]);

This is what I tried

describe("Seo Directive", () => {
    const $window = {};
    const navigationContext = {};
    const ROUTE_STATES = {};
    const $location = {};
    const bfSport = {};

    beforeEach(() => {
        $location.protocol = jest.fn();
        $location.host = jest.fn();
        $location.port = jest.fn();

        navigationContext.view = jest.fn();
    });
    it("should return the sport name in EN", () => {

    });
});
skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • so you want to mock dependencies(`$window, navigationContext, ROUTE_STATES, $location, bfSport`), don't you? [`angular-mocks`](https://www.npmjs.com/package/angular-mocks) may [help you](https://curtistimson.co.uk/post/angularjs/angularjs-jest-unit-testing/) on that. see example in [different question at SO](https://stackoverflow.com/questions/43110646/unit-testing-angular-directives-with-jest) – skyboyer Aug 23 '19 at 09:49
  • I have seen that example as what I have tried is taken from there. I am new to Jest and Angular and I don't know how they are used. How should you test the getSportNameEN function? For id 1 the return string should be "fotball" for example. – Lucia Bondar Aug 23 '19 at 10:20
  • oh, I see. no, you will never access local variables/functions inside closure. but you don't actually need that. focus on how that function is used by directive. Say if that function is used to return different text - that compose few `it()` where each will render directive with different input. and you verify here content is you expect. – skyboyer Aug 23 '19 at 10:34
  • and how do you render the directive with different input? or how do you mock it? – Lucia Bondar Aug 23 '19 at 10:47
  • by links above they validates `element.html()` output as render's result – skyboyer Aug 23 '19 at 11:21

0 Answers0