Best JavaScript code snippet using ng-mocks
list-alerts-spec.js
Source:list-alerts-spec.js  
1/**2 * Copyright (c) 2014 Intel Corporation3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *    http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16'use strict';17describe('list alerts', function() {18    var scope,19        rootScope,20        location,21        controllerProvider,22        ctrl,23        ngTableParams = function () {24            this.reload = sinon.spy();25        },26        ngProgressStub;27    var ModalMock = function () {28        var self = this;29        this.open = function (config) {30            return {31                result: {32                    config: config,33                    then: function (confirm, cancel) {34                        self.confirm = confirm;35                        self.cancel = cancel;36                    }37                },38                close: function (res) {39                    if (self.confirm) {40                        self.confirm(res);41                    }42                },43                dismiss: function () {44                    if (self.cancel) {45                        self.cancel();46                    }47                }48            };49        };50    };51    beforeEach(module('iotController'));52    beforeEach(module('ngProgress'));53    beforeEach(inject(function ($controller, $rootScope, $location, ngProgress) {54        rootScope = $rootScope;55        scope = $rootScope.$new();56        scope.$parent = {57            i18n:{58                alerts:{59                    title:'test',60                    errors: {61                        updateAlerts: 'test'62                    }63                }64            }65        }66        scope.$on = function(value, callback) { };67        controllerProvider = $controller;68        location = $location;69        ngProgressStub = sinon.stub(ngProgress);70    }));71    it('should change selected menu to "alerts"', function(){72        ctrl = controllerProvider('ListAlertsCtrl', {73            $scope: scope,74            $routeParams: {},75            $location: {},76            $filter:{},77            $modal: {},78            $q: {},79            alertsService: {},80            orderingService: {},81            filteringService: {},82            sessionService: {},83            ngTableParams: ngTableParams,84            ngProgress: ngProgressStub85        });86        expect(scope.$parent.page.menuSelected).to.equal('alerts');87    });88    it('should create "alerts" model with no alerts', function(){89        ctrl = controllerProvider('ListAlertsCtrl', {90            $scope: scope,91            $routeParams: {},92            $location: {},93            $filter:{},94            $modal: {},95            $q: {},96            alertsService: {},97            orderingService: {},98            filteringService: {},99            sessionService: {},100            ngTableParams: ngTableParams,101            ngProgress: ngProgressStub102        });103        expect(scope.alerts.length).to.equal(0);104    });105    it('should return status to filter with', function(){106        // prepare107        var defMock = {108                resolve: sinon.spy()109            },110            qMock = {111                defer: sinon.stub()112            };113        qMock.defer.withArgs().returns(defMock);114        ctrl = controllerProvider('ListAlertsCtrl', {115            $scope: scope,116            $routeParams: {},117            $location: {},118            $filter:{},119            $modal: {},120            $q: qMock,121            alertsService: {},122            orderingService: {},123            filteringService: {},124            sessionService: {},125            ngTableParams: ngTableParams,126            ngProgress: ngProgressStub127        });128        // execute129        scope.getStatusesToFilterWith();130        // assert131        expect(qMock.defer.calledOnce).to.equal(true);132        expect(defMock.resolve.calledOnce).to.equal(true);133        expect(defMock.resolve.args[0].length).to.equal(1);134        var actual = defMock.resolve.args[0][0];135        expect(actual.length).to.equal(3);136        expect(actual[0].id).to.equal('New');137        expect(actual[0].title).to.equal('New');138        expect(actual[1].id).to.equal('Open');139        expect(actual[1].title).to.equal('Open');140        expect(actual[2].id).to.equal('Closed');141        expect(actual[2].title).to.equal('Closed');142    });143    it('should return priorities to filter with', function(){144        // prepare145        var defMock = {146                resolve: sinon.spy()147            },148            qMock = {149                defer: sinon.stub()150            };151        qMock.defer.withArgs().returns(defMock);152        ctrl = controllerProvider('ListAlertsCtrl', {153            $scope: scope,154            $routeParams: {},155            $location: {},156            $filter:{},157            $modal: {},158            $q: qMock,159            alertsService: {},160            orderingService: {},161            filteringService: {},162            sessionService: {},163            ngTableParams: ngTableParams,164            ngProgress: ngProgressStub165        });166        // execute167        scope.getPrioritiesToFilterWith();168        // assert169        expect(qMock.defer.calledOnce).to.equal(true);170        expect(defMock.resolve.calledOnce).to.equal(true);171        expect(defMock.resolve.args[0].length).to.equal(1);172        var actual = defMock.resolve.args[0][0];173        expect(actual.length).to.equal(3);174        expect(actual[0].id).to.equal('High');175        expect(actual[0].title).to.equal('High');176        expect(actual[1].id).to.equal('Medium');177        expect(actual[1].title).to.equal('Medium');178        expect(actual[2].id).to.equal('Low');179        expect(actual[2].title).to.equal('Low');180    });181    it('should change status of given alert if user confirms the change - to open', function(){182        // prepare183        var alert = {184                alertId: 1185            },186            newStatus = 'Open',187            serviceMock = {188                updateStatus: sinon.stub().callsArgWith(1),189                reset: sinon.spy()190            };191        ctrl = controllerProvider('ListAlertsCtrl', {192            $scope: scope,193            $routeParams: {},194            $location: {},195            $filter:{},196            $modal: new ModalMock(),197            $q: {},198            alertsService: serviceMock,199            orderingService: {},200            filteringService: {},201            sessionService: {},202            ngTableParams: ngTableParams,203            ngProgress: ngProgressStub204        });205        // execute206        var modalInstance = scope.changeStatus(alert, newStatus);207        var modalCtrl = new modalInstance.result.config.controller(scope, modalInstance, alert, newStatus);208        scope.confirm();209        // assert210        expect(serviceMock.reset.calledOnce).to.equal(false);211        expect(serviceMock.updateStatus.calledOnce).to.equal(true);212        expect(serviceMock.updateStatus.args[0].length).to.equal(3);213        expect(serviceMock.updateStatus.args[0][0].alert.alertId).to.equal(alert.alertId);214        expect(serviceMock.updateStatus.args[0][0].newStatus).to.equal(newStatus);215        expect(scope.tableAlerts.reload.calledOnce).to.equal(true);216        expect(scope.error).to.be.null;217    });218    it('should change status of given alert if user confirms the change - to new', function(){219        // prepare220        var alert = {221                alertId: 1222            },223            newStatus = 'Open',224            serviceMock = {225                updateStatus: sinon.stub().callsArgWith(1),226                reset: sinon.spy()227            };228        ctrl = controllerProvider('ListAlertsCtrl', {229            $scope: scope,230            $routeParams: {},231            $location: {},232            $filter:{},233            $modal: new ModalMock(),234            $q: {},235            alertsService: serviceMock,236            orderingService: {},237            filteringService: {},238            sessionService: {},239            ngTableParams: ngTableParams,240            ngProgress: ngProgressStub241        });242        // execute243        var modalInstance = scope.changeStatus(alert, newStatus);244        var modalCtrl = new modalInstance.result.config.controller(scope, modalInstance, alert, newStatus);245        scope.confirm();246        // assert247        expect(serviceMock.reset.calledOnce).to.equal(false);248        expect(serviceMock.updateStatus.calledOnce).to.equal(true);249        expect(serviceMock.updateStatus.args[0].length).to.equal(3);250        expect(serviceMock.updateStatus.args[0][0].alert.alertId).to.equal(alert.alertId);251        expect(serviceMock.updateStatus.args[0][0].newStatus).to.equal(newStatus);252        expect(scope.tableAlerts.reload.calledOnce).to.equal(true);253        expect(scope.error).to.be.null;254    });255    it('should not change status of given alert if user cancels the change', function(){256        // prepare257        var alert = {258                alertId: 1259            },260            newStatus = 'Open',261            serviceMock = {262                updateStatus: sinon.stub().callsArgWith(1),263                reset: sinon.spy()264            };265        ctrl = controllerProvider('ListAlertsCtrl', {266            $scope: scope,267            $routeParams: {},268            $location: {},269            $filter:{},270            $modal: new ModalMock(),271            $q: {},272            alertsService: serviceMock,273            orderingService: {},274            filteringService: {},275            sessionService: {},276            ngTableParams: ngTableParams,277            ngProgress: ngProgressStub278        });279        // execute280        var modalInstance = scope.changeStatus(alert, newStatus);281        var modalCtrl = new modalInstance.result.config.controller(scope, modalInstance, alert, newStatus);282        scope.cancel();283        // assert284        expect(serviceMock.reset.calledOnce).to.equal(false);285        expect(serviceMock.updateStatus.calledOnce).to.equal(false);286        expect(scope.tableAlerts.reload.calledOnce).to.equal(false);287        expect(scope.error).to.be.null;288    });289    it('should not change status of given alert if user cancels the change', function(){290        // prepare291        var alert = {292                alertId: 1293            },294            newStatus = 'Open',295            serviceMock = {296                updateStatus: sinon.stub().callsArgWith(1),297                reset: sinon.spy()298            };299        ctrl = controllerProvider('ListAlertsCtrl', {300            $scope: scope,301            $routeParams: {},302            $location: {},303            $filter:{},304            $modal: new ModalMock(),305            $q: {},306            alertsService: serviceMock,307            orderingService: {},308            filteringService: {},309            sessionService: {},310            ngTableParams: ngTableParams,311            ngProgress: ngProgressStub312        });313        // execute314        var modalInstance = scope.changeStatus(alert, newStatus);315        var modalCtrl = new modalInstance.result.config.controller(scope, modalInstance, alert, newStatus);316        scope.cancel();317        // assert318        expect(serviceMock.reset.calledOnce).to.equal(false);319        expect(serviceMock.updateStatus.calledOnce).to.equal(false);320        expect(scope.tableAlerts.reload.calledOnce).to.equal(false);321        expect(scope.error).to.be.null;322    });323    it('should reset given alert if user confirms the change', function(){324        // prepare325        var alert = {326                alertId: 1327            },328            newStatus = 'Closed',329            serviceMock = {330                updateStatus: sinon.spy(),331                reset: sinon.stub().callsArgWith(1)332            };333        ctrl = controllerProvider('ListAlertsCtrl', {334            $scope: scope,335            $routeParams: {},336            $location: {},337            $filter:{},338            $modal: new ModalMock(),339            $q: {},340            alertsService: serviceMock,341            orderingService: {},342            filteringService: {},343            sessionService: {},344            ngTableParams: ngTableParams,345            ngProgress: ngProgressStub346        });347        // execute348        var modalInstance = scope.changeStatus(alert, newStatus);349        var modalCtrl = new modalInstance.result.config.controller(scope, modalInstance, alert, newStatus);350        scope.confirm();351        // assert352        expect(serviceMock.updateStatus.calledOnce).to.equal(false);353        expect(serviceMock.reset.calledOnce).to.equal(true);354        expect(serviceMock.reset.args[0].length).to.equal(3);355        expect(serviceMock.reset.args[0][0].alert.alertId).to.equal(alert.alertId);356        expect(scope.tableAlerts.reload.calledOnce).to.equal(true);357        expect(scope.error).to.be.null;358    });359    it('should not change status of given alert if something goes wrong', function(){360        // prepare361        var alert = {362                alertId: 1363            },364            newStatus = 'Open',365            serviceMock = {366                updateStatus: sinon.stub().callsArgWith(2), // trigger an error367                reset: sinon.spy()368            };369        ctrl = controllerProvider('ListAlertsCtrl', {370            $scope: scope,371            $routeParams: {},372            $location: {},373            $filter:{},374            $modal: new ModalMock(),375            $q: {},376            alertsService: serviceMock,377            orderingService: {},378            filteringService: {},379            sessionService: {},380            ngTableParams: ngTableParams,381            ngProgress: ngProgressStub382        });383        // execute384        var modalInstance = scope.changeStatus(alert, newStatus);385        var modalCtrl = new modalInstance.result.config.controller(scope, modalInstance, alert, newStatus);386        scope.confirm();387        // assert388        expect(serviceMock.reset.calledOnce).to.equal(false);389        expect(serviceMock.updateStatus.calledOnce).to.equal(true);390        expect(scope.tableAlerts.reload.calledOnce).to.equal(false);391        expect(scope.error).to.equal(scope.$parent.i18n.alerts.errors.updateAlerts);392    });393    it('should open details of given alert - status = New - status changed successfully', function(){394        // prepare395        var alert = {396                alertId: 10,397                status: 'New'398            },399            serviceMock = {400                updateStatus: sinon.stub().callsArgWith(1)401            };402        ctrl = controllerProvider('ListAlertsCtrl', {403            $scope: scope,404            $routeParams: {},405            $location: location,406            $filter:{},407            $modal: {},408            $q: {},409            alertsService: serviceMock,410            orderingService: {},411            filteringService: {},412            sessionService: {},413            ngTableParams: ngTableParams,414            ngProgress: ngProgressStub415        });416        // execute417        scope.openDetails(alert);418        // attest419        expect(serviceMock.updateStatus.calledOnce).to.equal(true);420        expect(location.path()).to.contain('/alerts/edit/' + alert.alertId);421    });422    it('should open details of given alert - status = New - status changed failed', function(){423        // prepare424        var alert = {425                alertId: 10,426                status: 'New'427            },428            serviceMock = {429                updateStatus: sinon.stub().callsArgWith(2)430            };431        ctrl = controllerProvider('ListAlertsCtrl', {432            $scope: scope,433            $routeParams: {},434            $location: location,435            $filter:{},436            $modal: {},437            $q: {},438            alertsService: serviceMock,439            orderingService: {},440            filteringService: {},441            sessionService: {},442            ngTableParams: ngTableParams,443            ngProgress: ngProgressStub444        });445        // execute446        scope.openDetails(alert);447        // attest448        expect(serviceMock.updateStatus.calledOnce).to.equal(true);449        expect(location.path()).to.contain('/alerts/edit/' + alert.alertId);450    });451    it('should open details of given alert - status != New', function(){452        // prepare453        var alert = {454                alertId: 10,455                status: 'Closed'456            },457            serviceMock = {458                updateStatus: sinon.spy()459            };460        ctrl = controllerProvider('ListAlertsCtrl', {461            $scope: scope,462            $routeParams: {},463            $location: location,464            $filter:{},465            $modal: {},466            $q: {},467            alertsService: serviceMock,468            orderingService: {},469            filteringService: {},470            sessionService: {},471            ngTableParams: ngTableParams,472            ngProgress: ngProgressStub473        });474        // execute475        scope.openDetails(alert);476        // attest477        expect(serviceMock.updateStatus.calledOnce).to.equal(false);478        expect(location.path()).to.contain('/alerts/edit/' + alert.alertId);479    });...edit-alert-spec.js
Source:edit-alert-spec.js  
1/**2 * Copyright (c) 2014 Intel Corporation3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *    http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16describe('edit alert', function() {17    var scope,18        rootScope,19        location,20        controllerProvider,21        ctrl,22        rulesServiceMock = {23            getRuleById: sinon.spy()24        };25    beforeEach(module('iotController'));26    beforeEach(inject(function ($controller, $rootScope, $location) {27        rootScope = $rootScope;28        scope = $rootScope.$new();29        scope.$parent = {30            i18n:{31                alerts:{32                    title:'test',33                    errors: {34                        loadAlerts: 'test',35                        updateAlerts: 'test'36                    }37                }38            }39        };40        controllerProvider = $controller;41        location = $location;42    }));43    it('should change selected menu to "alerts" and other initializations', function(){44        // prepare45        var serviceMock = {46            getAlert: sinon.spy()47        };48        ctrl = controllerProvider('EditAlertCtrl', {49            $scope: scope,50            $routeParams: {},51            $location: {},52            alertsService: serviceMock,53            rulesService: rulesServiceMock54        });55        // attest56        expect(scope.$parent.page.menuSelected).to.equal('alerts');57        expect(scope.statusEdit).to.equal(false);58        expect(scope.error).to.equal(null);59        expect(scope.alert).to.equal(null);60        expect(scope.currentComment).to.equal(null);61        expect(scope.addingComment).to.equal(false);62        expect(scope.comments.length).to.equal(0);63        expect(serviceMock.getAlert.calledOnce).to.equal(true);64    });65    it('should request given alert at initialization', function(){66        // prepare67        var alert = {68                alertId: 1,69                status: 'Open',70                comments: [{}]71            },72            serviceMock = {73                getAlert: sinon.stub().callsArgWith(1, alert)74            },75            routeParamsMock = {76                alertId: alert.alertId77            };78        ctrl = controllerProvider('EditAlertCtrl', {79            $scope: scope,80            $routeParams: routeParamsMock,81            $location: {},82            alertsService: serviceMock,83            rulesService: rulesServiceMock84        });85        // attest86        expect(scope.alert.alertId).to.equal(alert.alertId);87        expect(scope.error).to.equal(null);88        expect(scope.comments.length).to.equal(1);89        expect(scope.currentStatus.name).to.equal(alert.status);90        expect(serviceMock.getAlert.calledOnce).to.equal(true);91    });92    it('should request given alert at initialization - request failed', function(){93        // prepare94        var alert = {95                alertId: 1,96                status: 'Open',97                comments: [{}]98            },99            serviceMock = {100                getAlert: sinon.stub().callsArgWith(2)101            },102            routeParamsMock = {103                alertId: alert.alertId104            };105        ctrl = controllerProvider('EditAlertCtrl', {106            $scope: scope,107            $routeParams: routeParamsMock,108            $location: {},109            alertsService: serviceMock,110            rulesService: rulesServiceMock111        });112        // attest113        expect(scope.alert).to.equal(null);114        expect(scope.error).to.equal(scope.$parent.i18n.alerts.errors.loadAlerts);115        expect(scope.comments.length).to.equal(0);116        expect(serviceMock.getAlert.calledOnce).to.equal(true);117    });118    it('should add a comment when requested by user', function(){119        // prepare120        var user = {121                email: 'user1@mail.com'122            },123            alert = {124                alertId: 1125            },126            comment = Math.random().toString(),127            serviceMock = {128                getAlert: sinon.stub().callsArgWith(1, alert),129                addComments: sinon.stub().callsArgWith(1)130            };131        scope.$root = { currentUser: user };132        ctrl = controllerProvider('EditAlertCtrl', {133            $scope: scope,134            $routeParams: {},135            $location: {},136            alertsService: serviceMock,137            rulesService: rulesServiceMock138        });139        // execute140        scope.addComment(comment);141        // attest142        expect(scope.comments.length).to.equal(1);143        expect(scope.comments[0].text).to.equal(comment);144        expect(scope.currentComment).to.equal(null);145        expect(scope.addingComment).to.equal(false);146        expect(serviceMock.getAlert.calledOnce).to.equal(true);147        expect(serviceMock.addComments.calledOnce).to.equal(true);148    });149    it('should add a comment when requested by user (only at memory) - request failed', function(){150        // prepare151        var user = {152                email: 'user1@mail.com'153            },154            alert = {155                alertId: 1156            },157            comment = Math.random().toString(),158            serviceMock = {159                getAlert: sinon.stub().callsArgWith(1, alert),160                addComments: sinon.stub().callsArgWith(2)161            };162        scope.$root = { currentUser: user };163        ctrl = controllerProvider('EditAlertCtrl', {164            $scope: scope,165            $routeParams: {},166            $location: {},167            alertsService: serviceMock,168            rulesService: rulesServiceMock169        });170        // execute171        scope.addComment(comment);172        // attest173        expect(scope.comments.length).to.equal(1);174        expect(scope.comments[0].text).to.equal(comment);175        expect(scope.currentComment).to.equal(null);176        expect(scope.addingComment).to.equal(false);177        expect(serviceMock.getAlert.calledOnce).to.equal(true);178        expect(serviceMock.addComments.calledOnce).to.equal(true);179    });180    it('should not add a comment when requested by user if it is empty', function(){181        // prepare182        var user = {183                email: 'user1@mail.com'184            },185            alert = {186                alertId: 1187            },188            comment = undefined,189            serviceMock = {190                getAlert: sinon.stub().callsArgWith(1, alert),191                addComments: sinon.stub().callsArgWith(1)192            };193        scope.$root = { currentUser: user };194        ctrl = controllerProvider('EditAlertCtrl', {195            $scope: scope,196            $routeParams: {},197            $location: {},198            alertsService: serviceMock,199            rulesService: rulesServiceMock200        });201        // execute202        scope.addComment(comment);203        // attest204        expect(scope.comments.length).to.equal(0);205        expect(serviceMock.getAlert.calledOnce).to.equal(true);206        expect(serviceMock.addComments.calledOnce).to.equal(false);207    });208    it('should parse timestamp', function(){209        // prepare210        var serviceMock = {211            getAlert: sinon.spy()212        };213        ctrl = controllerProvider('EditAlertCtrl', {214            $scope: scope,215            $routeParams: {},216            $location: {},217            alertsService: serviceMock,218            rulesService: rulesServiceMock219        });220        // execute221        var actual = scope.parseTimestamp(Date.now());222        // attest223        expect(actual).not.to.be.a('undefined');224    });225    it('should change status when requested by user - status = New', function(){226        // prepare227        var alert = {228                alertId: 1,229                status: 'New'230            },231            serviceMock = {232                getAlert: sinon.stub().callsArgWith(1, alert),233                updateStatus: sinon.stub().callsArgWith(1),234                reset: sinon.spy()235            };236        ctrl = controllerProvider('EditAlertCtrl', {237            $scope: scope,238            $routeParams: {},239            $location: {},240            alertsService: serviceMock,241            rulesService: rulesServiceMock242        });243        // execute244        scope.changeStatus();245        // attest246        expect(scope.error).to.equal(null);247        expect(serviceMock.getAlert.calledOnce).to.equal(true);248        expect(serviceMock.updateStatus.calledOnce).to.equal(true);249        expect(serviceMock.reset.calledOnce).to.equal(false);250    });251    it('should change status when requested by user - status = New - request failed', function(){252        // prepare253        var alert = {254                alertId: 1,255                status: 'New'256            },257            serviceMock = {258                getAlert: sinon.stub().callsArgWith(1, alert),259                updateStatus: sinon.stub().callsArgWith(2),260                reset: sinon.spy()261            };262        ctrl = controllerProvider('EditAlertCtrl', {263            $scope: scope,264            $routeParams: {},265            $location: {},266            alertsService: serviceMock,267            rulesService: rulesServiceMock268        });269        // execute270        scope.changeStatus();271        // attest272        expect(scope.error).to.equal(scope.$parent.i18n.alerts.errors.updateAlerts);273        expect(serviceMock.getAlert.calledOnce).to.equal(true);274        expect(serviceMock.updateStatus.calledOnce).to.equal(true);275        expect(serviceMock.reset.calledOnce).to.equal(false);276    });277    it('should change status when requested by user - status = Closed', function(){278        // prepare279        var alert = {280                alertId: 1,281                status: 'Closed'282            },283            serviceMock = {284                getAlert: sinon.stub().callsArgWith(1, alert),285                updateStatus: sinon.spy(),286                reset: sinon.stub().callsArgWith(1)287            };288        ctrl = controllerProvider('EditAlertCtrl', {289            $scope: scope,290            $routeParams: {},291            $location: {},292            alertsService: serviceMock,293            rulesService: rulesServiceMock294        });295        // execute296        scope.changeStatus();297        // attest298        expect(scope.error).to.equal(null);299        expect(serviceMock.getAlert.calledOnce).to.equal(true);300        expect(serviceMock.updateStatus.calledOnce).to.equal(false);301        expect(serviceMock.reset.calledOnce).to.equal(true);302    });303    it('should go to /alerts when user clicks Close button', function(){304        // prepare305        var serviceMock = {306            getAlert: sinon.spy()307        };308        ctrl = controllerProvider('EditAlertCtrl', {309            $scope: scope,310            $routeParams: {},311            $location: location,312            alertsService: serviceMock,313            rulesService: rulesServiceMock314        });315        // execute316        scope.close();317        // attest318        expect(location.path()).to.equal('/alerts');319    });...ServiceReceiver.test.js
Source:ServiceReceiver.test.js  
1const { balance, ether, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');2const { expect } = require('chai');3const { shouldBehaveLikeOwnable } = require('../access/Ownable.behavior');4const ServiceReceiver = artifacts.require('ServiceReceiver');5contract('ServiceReceiver', function ([owner, thirdParty]) {6  const fee = ether('0.1');7  context('ServiceReceiver behaviours', function () {8    beforeEach(async function () {9      this.serviceReceiver = await ServiceReceiver.new({ from: owner });10    });11    describe('set price', function () {12      context('when the sender is owner', function () {13        it('should set price', async function () {14          await this.serviceReceiver.setPrice('ServiceMock', fee, { from: owner });15          (await this.serviceReceiver.getPrice('ServiceMock')).should.be.bignumber.equal(fee);16        });17      });18      context('when the sender is not owner', function () {19        it('reverts', async function () {20          await expectRevert(21            this.serviceReceiver.setPrice('ServiceMock', fee, { from: thirdParty }),22            'Ownable: caller is not the owner',23          );24        });25      });26    });27    describe('pay', function () {28      context('with incorrect price', function () {29        it('reverts', async function () {30          await this.serviceReceiver.setPrice('ServiceMock', fee, { from: owner });31          await expectRevert(32            this.serviceReceiver.pay(33              'ServiceMock',34              {35                from: thirdParty,36                value: fee.add(ether('1')),37              },38            ),39            'ServiceReceiver: incorrect price',40          );41        });42      });43      context('with correct price', function () {44        beforeEach(async function () {45          await this.serviceReceiver.setPrice('ServiceMock', fee, { from: owner });46        });47        it('emits a Created event', async function () {48          const { logs } = await this.serviceReceiver.pay('ServiceMock', { value: fee, from: thirdParty });49          expectEvent.inLogs(logs, 'Created', {50            serviceName: 'ServiceMock',51            serviceAddress: thirdParty,52          });53        });54        it('transfer fee to receiver', async function () {55          const initBalance = await balance.current(this.serviceReceiver.address);56          await this.serviceReceiver.pay('ServiceMock', { value: fee, from: thirdParty });57          const newBalance = (await balance.current(this.serviceReceiver.address));58          expect(newBalance).to.be.bignumber.equal(initBalance.add(fee));59        });60      });61    });62    describe('withdraw', function () {63      beforeEach(async function () {64        await this.serviceReceiver.setPrice('ServiceMock', fee, { from: owner });65        await this.serviceReceiver.pay('ServiceMock', { value: fee, from: thirdParty });66      });67      context('when the sender is owner', function () {68        it('should withdraw', async function () {69          const amount = ether('0.05');70          const contractBalanceTracker = await balance.tracker(this.serviceReceiver.address);71          const ownerBalanceTracker = await balance.tracker(owner);72          await this.serviceReceiver.withdraw(amount, { from: owner, gasPrice: 0 });73          expect(await contractBalanceTracker.delta()).to.be.bignumber.equal(amount.neg());74          expect(await ownerBalanceTracker.delta()).to.be.bignumber.equal(amount);75        });76      });77      context('when the sender is not owner', function () {78        it('reverts', async function () {79          const amount = ether('0.05');80          await expectRevert(81            this.serviceReceiver.withdraw(amount, { from: thirdParty }),82            'Ownable: caller is not the owner',83          );84        });85      });86    });87    context('like a Ownable', function () {88      beforeEach(async function () {89        this.ownable = this.serviceReceiver;90      });91      shouldBehaveLikeOwnable(owner, [thirdParty]);92    });93  });...Using AI Code Generation
1import { serviceMock } from 'ng-mocks';2import { MyService } from './my.service';3import { MyComponent } from './my.component';4describe('MyComponent', () => {5  let component: MyComponent;6  let service: MyService;7  beforeEach(() => {8    service = serviceMock(MyService);9    component = new MyComponent(service);10  });11  it('should create', () => {12    expect(component).toBeTruthy();13  });14});15import { Injectable } from '@angular/core';16@Injectable()17export class MyService {18  public getValue(): number {19    return 42;20  }21}22import { Component } from '@angular/core';23import { MyService } from './my.service';24@Component({25})26export class MyComponent {27  public value: number;28  constructor(private service: MyService) {29    this.value = this.service.getValue();30  }31}32import { serviceMock } from 'ng-mocks';33import { MyService } from './my.service';34import { MyComponent } from './my.component';35describe('MyComponent', () => {36  let component: MyComponent;37  let service: MyService;38  beforeEach(() => {39    service = serviceMock(MyService);40    component = new MyComponent(service);41  });42  it('should create', () => {43    expect(component).toBeTruthy();44  });45});46import { Injectable } from '@angular/core';47@Injectable()48export class MyService {49  public getValue(): number {50    return 42;51  }52}53import { Component } from '@angular/core';54import { MyService } from './my.service';55@Component({56})57export class MyComponent {58  public value: number;59  constructor(private service: MyService) {60    this.value = this.service.getValue();61  }62}63import { serviceMock } from 'ng-mocks';64import { MyService } from './my.service';65import { MyComponent } from './my.component';66describe('MyComponent', () => {67  let component: MyComponent;68  let service: MyService;69  beforeEach(() => {70    service = serviceMock(MyService);Using AI Code Generation
1import { serviceMock } from 'ng-mocks';2import { SomeService } from './some.service';3describe('Service Mock', () => {4  it('should mock service', () => {5    const service = serviceMock(SomeService);6    service.testMethod.and.returnValue('mocked value');7    expect(service.testMethod()).toBe('mocked value');8  });9});10import { Injectable } from '@angular/core';11import { SomeOtherService } from './some-other.service';12@Injectable()13export class SomeService {14  constructor(private someOtherService: SomeOtherService) {}15  testMethod() {16    return this.someOtherService.testMethod();17  }18}19import { Injectable } from '@angular/core';20@Injectable()21export class SomeOtherService {22  testMethod() {23    return 'some value';24  }25}26import { serviceMock } from 'ng-mocks';27import { SomeService } from './some.service';28import { SomeOtherService } from './some-other.service';29describe('Service Mock', () => {30  it('should mock service', () => {31    const service = serviceMock(SomeService, {32      someOtherService: serviceMock(SomeOtherService),33    });34    service.testMethod.and.returnValue('mocked value');35    expect(service.testMethod()).toBe('mocked value');36  });37});38import { InjectableUsing AI Code Generation
1import { serviceMock } from 'ng-mocks';2import { AuthService } from './auth.service';3import { TestBed } from '@angular/core/testing';4import { HttpClientTestingModule } from '@angular/common/http/testing';5import { RouterTestingModule } from '@angular/router/testing';6import { ToastrModule } from 'ngx-toastr';7describe('AuthService', () => {8  let service: AuthService;9  beforeEach(() => {10    TestBed.configureTestingModule({11      imports: [12        ToastrModule.forRoot(),13    });14    service = TestBed.inject(AuthService);15  });16  it('should be created', () => {17    expect(service).toBeTruthy();18  });19  it('should be called the serviceMock', () => {20    const mockService = serviceMock(AuthService);21    expect(mockService).toBeTruthy();22  });23});Using AI Code Generation
1var serviceMock = ngMocks.serviceMock('service', {2  method: () => 'mocked'3});4var serviceSpy = ngMocks.serviceSpy('service', {5  method: () => 'spied'6});7var serviceMock = ngMocks.serviceMock('service', {8  method: () => 'mocked'9});10var serviceSpy = ngMocks.serviceSpy('service', {11  method: () => 'spied'12});13var serviceMock = ngMocks.serviceMock('service', {14  method: () => 'mocked'15});16var serviceSpy = ngMocks.serviceSpy('service', {17  method: () => 'spied'18});19var serviceMock = ngMocks.serviceMock('service', {20  method: () => 'mocked'21});22var serviceSpy = ngMocks.serviceSpy('service', {23  method: () => 'spied'24});25var serviceMock = ngMocks.serviceMock('service', {26  method: () => 'mocked'27});28var serviceSpy = ngMocks.serviceSpy('service', {29  method: () => 'spied'30});31var serviceMock = ngMocks.serviceMock('service', {32  method: () => 'mocked'33});34var serviceSpy = ngMocks.serviceSpy('service', {35  method: () => 'spied'36});37var serviceMock = ngMocks.serviceMock('service', {38  method: () => 'mocked'39});40var serviceSpy = ngMocks.serviceSpy('service', {41  method: () => 'spied'42});Using AI Code Generation
1import { serviceMock } from 'ng-mocks';2describe('Test', () => {3    it('test', () => {4        const service = serviceMock('service');5        service.method();6    });7});8import { serviceMock } from 'ng-mocks';9import { Service } from './service';10describe('Test', () => {11    it('test', () => {12        const service = serviceMock(Service);13        service.method();14    });15});16import { serviceMock } from 'ng-mocks';17import { Service } from './service';18describe('Test', () => {19    it('test', () => {20        const service = serviceMock(Service);21        service.method();22    });23});24import { serviceMock } from 'ng-mocks';25import { Service } from './service';26describe('Test', () => {27    it('test', () => {28        const service = serviceMock(Service);29        service.method();30    });31});32import { serviceMock } from 'ng-mocks';33import { Service } from './service';34describe('Test', () => {35    it('test', () => {36        const service = serviceMock(Service);37        service.method();38    });39});40import { serviceMock } from 'ng-mocks';41import { Service } from './service';42describe('Test', () => {43    it('test', () => {44        const service = serviceMock(Service);45        service.method();46    });47});48import { serviceMock } from 'ng-mocks';49import { Service } from './service';50describe('Test', () => {51    it('test', () => {52        const service = serviceMock(Service);53        service.method();54    });55});56import { serviceMock } from 'ng-mocks';57import { Service } from './service';58describe('Test', () => {59    it('testUsing AI Code Generation
1import { serviceMock } from 'ng-mocks';2describe('TestService', () => {3  it('should return the correct value', () => {4    const service = serviceMock({5      get: () => {6        return 'test';7      }8    });9    expect(service.get()).toEqual('test');10  });11});12serviceMock({ get: () => { return 'test'; } }, 'TestService');13serviceMock({ get: () => { return 'test'; } }, 'TestService');14serviceMock({ get: () => { return 'test'; } }, 'TestService');15serviceMock({ get: () => { return 'test'; } }, 'TestService');16serviceMock({ get: () => { return 'test'; } }, 'TestService');17serviceMock({ get: () => { return 'test'; } }, 'TestService');18serviceMock({ get: () => { return 'test'; } }, 'TestService');Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
