I can't figure out why I keep receiving this Angular-Mock error and my Mocha test won't seem to

I encountered the same exact error message as detailed here: (window.beforeEach || window.setup) is not a function. Despite trying the suggested fix, the tutorial author here also recommended the same solution.

This is the proposed fix by the Tuts+ author: https://i.sstatic.net/NRAgp.jpg

The fix involves moving the angular-mock script tag below the Mochai and Chai scripts. I followed this arrangement as shown below:

https://i.sstatic.net/idT70.png

test/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Mocha Spec Runner</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="icon" href="../app/favicon.ico">
    <link rel="apple-touch-icon" href="../app/assets/imgs/apple-touch-icon.png">
    <link href="bower_components/mocha/mocha.css" rel="stylesheet">
</head>

<body>

    <div id="mocha"></div>

    <script src="../bower_components/angular/angular.js"></script>
    <script src="../bower_components/mocha/mocha.js"></script>
    <script src="../bower_components/chai/chai.js"></script>
    <!-- Angular-mocks inclusion placed after Mocha and Chai -->
    <script src="../bower_components/angular-mocks/angular-mocks.js"></script>

    <script>
        mocha.setup('bdd');
    </script>

    <script src="main.spec.js"></script>

    <script>
        mocha.run();
    </script>

</body>
</html>

My main.spec.js file

/**
 * @name Mocha Test Runner
 * @desc Describes and executes our dashboard tests
 */

var assert = chai.assert;
var expect = chai.expect;

// Deliberately failing test case
describe('User Login', function() {
    console.log('User Login');
    describe('Login Failed', function() {
        console.log('Login Failed');
        if ('Incorrect login should fail', function() {
            module('loginController')
            inject(function($injector) {
                apiFactory = $injector.get('ApiFactory');
            });

            expect(apiFactory).to.be.an('number');
        });
    });    
});

My Gulp tasks

gulp.task('serve', function() {
    return browserSync.init({
        notify : false,
        port   : 3333,
        server: {
            baseDir: ['app'],
            routes: {
                '/bower_components' : 'bower_components'
            }
        }
    });
});

gulp.task('serve-test', function() {
    browserSync.init({
        notify : false,
        port   : 4444,
        server: {
            baseDir: ['test', 'app'],
            routes: {
                '/bower_components' : 'bower_components'
            }
        }
    });
});

Answer №1

Ensure that in your index.html file, you are including the angular-mocks.js script prior to calling mocha.setup('bdd'). The angular-mocks.js script is set up as an immediately-invoked function expression which relies on window.beforeEach. (https://github.com/angular/bower-angular-mocks/blob/master/angular-mocks.js#L2586)

It's worth noting that mocha.js needs to be manually invoked and configured by using the mocha.setup function in order for its functionality to take effect within the runtime environment.

Consider rearranging the sequence of these script tags so that mocha.js is enlisted and initialized before angular-mocks.js.


<script src='bower_components/mocha/mocha.js'></script>
<script src='bower_components/chai/chai.js'></script>
<script>
    mocha.setup('bdd');
</script>
<script src="bower_components/angular-mocks/angular-mocks.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Each time the page renders, LocalStorage is initialized with a fresh empty array

I've encountered an issue while trying to update my localStorage with new items added to my shopping cart. Each time an item is added, an empty array appears before it (see screenshot). Can anyone explain why this is happening? I'm considering u ...

How can I populate separate lists with data from an Angular GET request response?

I am new to using Angular and I have been struggling to build a frontend application that can consume my REST API created with Django. Despite searching for two days, I have not found a satisfactory answer to my problem. Chat GPT also seems to be inaccessi ...

Avoid losing any entered form information when leaving the page

As I work on creating a datagrid with hundreds of rows, each row features a checkbox that allows users to select items from the grid. I've noticed that users might spend considerable time filtering and searching through the grid, ticking checkboxes a ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Meteor push/browserhistory fails to navigate or refresh to a different page

Currently, I am attempting to set it up so that when a user clicks on a profile, they are redirected to the profile page of the user they clicked on. Here is the code I am using: const self = this; browserHistory.push({ pathname: '/user ...

What could be causing my Vuex state to remain unchanged even after the nuxtServerInit commit?

Although I've been utilizing the nuxtServerInit method to retrieve data from my Contentful CMS and commit the mutation to update the categories state object, I keep encountering an issue where categories remain empty even after attempting to display t ...

Exploring the dynamic changes in user authentication state with Angular Fire subscriptions

At the moment, I have been listening to authentication state changes in my ngOnInit method of my AppComponent: export class AppComponent implements OnInit { constructor(public fireAuth: AngularFireAuth) { } ngOnInit(): void { this.fireAuth.auth ...

Conceal Reveal Secret Script

Can you help me with a question regarding the spoiler on this specific page? Here is the link: When I click on Windows, a table appears. However, when I click on Linux, the content of Windows disappears. I am looking to create a spoiler like this, but whe ...

Is it possible to use Javascript to retrieve a variable from a remote PHP file?

I am trying to retrieve a variable from a remote PHP file using JavaScript in my phonegap application. The same origin policy doesn't apply here, so I believe I need to use JSON/AJAX for this task. However, I have been unable to find any tutorials tha ...

How can I use jQuery to implement a progress bar for Iframes loading?

My job involves working on an intranet where I have a complex aspx page with multiple Iframes, all of which we control. Each iframe is dynamically set using JavaScript/jQuery by different buttons on the page. Some buttons set the src attribute for iframes ...

Testing Angular controllers with mocked methods is an essential part of unit testing in Angular

I'm facing a challenge with mocking the method of service in the controller. While I know how to mock simple services like service.method, I am unsure about how to mock "action.user.update". Whenever I try to spy on it, I encounter an error saying &ap ...

Delayed execution not completely cancelled prior to component being unmounted

Alert: Avoid calling setState (or forceUpdate) on an unmounted component. While this won't cause any issues, it could suggest a memory problem in your application. Make sure to clean up all subscriptions and async tasks in the componentWillUnmount met ...

Zooming into mouse position within Three.js 3D Environment

I’m facing an issue with my project that utilizes Three.js and orbitControls.js for handling the camera. The scene consists of a simple cube and the camera. By default, the camera zooms in/out towards the center of the screen when using the mouse wheel. ...

What's going on with the background color? It doesn't seem

I have incorporated Bootstrap into my html code and I am attempting to modify the background color of a div when the screen resolution changes from large to medium or small. Even though I have added a class, the change does not reflect when adjusting the ...

Using a jQuery dialog box containing an embedded iframe

I'm attempting to utilize the jQuery UI dialog box in order to display an iframe. Unfortunately, I'm running into some issues with getting it to work. I suspect that I may have made a syntax error, possibly related to the quotation marks within t ...

Utilize the Multer file upload feature by integrating it into its own dedicated controller function

In my Express application, I decided to keep my routes.js file organized by creating a separate UploadController. Here's what it looks like: // UploadController.js const multer = require('multer') const storage = multer.diskStorage({ dest ...

Filtering the values of an array nested within objects

Imagine having a vast database of 10,000 cards and attempting to filter them based on the banlist_info.ban_ocg === "Forbidden" { id: 15341821, name: 'Dandylion', type: 'Effect Monster', desc: 'If this card is sen ...

A quick demonstration of the node.js console.clear() method in action with a straightforward code snippet

Can someone provide me with a clear example of how to use the console.clear() method from the console module in node.js? I've searched extensively on stackoverflow but haven't found anything useful. console.log("Content printed in file"); con ...

Exploring the scope of event listeners in jQuery's TimeCircles

Currently experimenting with the jquery timer known as "TimeCircles", which can be found here. I have successfully set up a minute / second timer for 30 minutes with an alert that triggers at 25 minutes. My goal is to implement an event when the timer hits ...

Having trouble with the JavaScript code for a basic GPA calculator?

I am having issues with my code for a basic grade calculator. Even though I can input numbers, the final grade is not displayed on the screen. Can someone please help me identify what mistake I might be making? Please ignore the Japanese text, as it's ...