PHP + Laravel + Vue - Unexpected token '<' at app.js - javascript

I have a PHP+Vue project that I inherited from another programmer. I know the code should work because it's currently hosted on a server and running.
I downloaded the files to make some changes, and tried to run it locally (using Wampserver). However, when I try to access the site I get Uncaught SyntaxError: Unexpected token '<' (at app.js:1:1).
What I tried:
Looking into app.js (and app.css for that matter) in DevTools shows an HTML file (seems to be from base.blade.php) instead of javascript code. I checked every app.js file I could find on the project's folder and found actual code.
It seems like the wrong file is being served, but I don't know why or how to fix it. I don't have any experience with PHP.
Code:
app.js:
require('./bootstrap');
window.Vue = require('vue');
const files = require.context('./components', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
const app = new Vue({
el: '#app',
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
bootstrap.js:
window._ = require('lodash');
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
base.blade.php:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>#yield('title')</title>
<link href="{{ env('APP_ENV') == 'development' ? mix('css/app.css') : asset('css/app.css') }}" rel="stylesheet" defer>
<script src="{{ env('APP_ENV') == 'development' ? mix('js/app.js') : asset('js/app.js') }}" defer></script>
{{-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> --}}
<link href="https://fonts.googleapis.com/css?family=Roboto:200,300,400,500,600,700,800,900" rel="stylesheet">
#stack('head')
#stack('style')
</head>
<body>
<div id="app">
#yield('main')
</div>
</body>
#stack('script')
</html>

Related

jQuery functions and libraries not works if I include app.js in blade file,

I have vue.js component of pusher notification system in my Laravel app and I have to install tinymce for blog posts.
MY tinymce and other jquery functions stops working if i add js/app.js in my main layout blade file. but everything works with normal jquery 3.4.1 public folder link. it is important for me to add app.js because of vue.js components here is my files code
main_layout.blade.php
{{--<script src="{{asset('js/app.js')}}" ></script>--}}
<script src="{{asset('Assets/bootstrap4/jquery-3.4.1.min.js')}}" ></script>
<script src="{{asset('node_modules/tinymce/tinymce.min.js')}}"></script>
<script src="{{asset('node_modules/tinymce/jquery.tinymce.min.js')}}"></script>
<script src="{{asset('node_modules/tinymce/themes/silver/theme.js')}}"></script
<script src="{{asset('Admin/vendor/js-cookie/js.cookie.js')}}"></script>
<script src="{{asset('Admin/vendor/jquery.scrollbar/jquery.scrollbar.min.js')}}"></script>
<script src="{{asset('Admin/vendor/jquery-scroll-lock/dist/jquery-scrollLock.min.js')}}"></script>
<script src="{{asset('plugins/sweetalert/sweetalert.min.js')}}"></script>
<script src="{{asset('plugins/select2/dist/js/select2.js')}}"></script>
<script src="{{asset('Admin/js/argon.js')}}"></script>
<script src="{{asset('js/script.js')}}"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".nav-link.collapseLink").click(function(){
$(this).children(".collapse").collapse('toggle');
});
})
</script>
#yield('javascript')
</body>
resources/js/bootstrap.js
window._ = require('lodash');
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true,
encrypted: true,
authEndpoint: "/broadcasting/auth",
namespace:'App.Notifications',
});
resource/js/app.js
require('./bootstrap');
window.Vue = require('vue');
Vue.component('notifications', require('./components/Notifications.vue').default);
window.onload = function () {
var app = new Vue({
el: '#app',
});
}
I have checked all my code and not found any other mistake, please suggest any solution for this, if I uncomment js/app.js and comment public folder jQuery, then all other libraries gives errors like they doesn't have jQuery with them. i have also tried defer in app.js script link.
If use public folder jquery like i have shown below then all my jquery functions works and also tinymce but then i am unable to use that vue.js component
Thanks
You have to reformat your code.
Jquery script line should be before the app.js line Eg.
<script src="{{asset('Assets/bootstrap4/jquery-3.4.1.min.js')}}" ></script>
<script src="{{ asset('js/app.js') }}"></script>

.NET Core 3.1 and Angular 9 web app build error(s)

I have developed a .NET Core 3.1 and Angular 9 web app in VSCode.
I have set up a launch.json file that serves the entire application (.NET Core and Angular 9) without a hitch.
I use the below angular.json settings when I run the ng build --prod to build the Angular 9 app and write it to the .NET Core wwwroot.
angular.json (extract)
"options": {
"outputPath": "../TargetPro.API/wwwroot",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": true,
"assets": [
"src/favicon.ico",
"src/assets",
"src/manifest.webmanifest"
],
"styles": [
"./node_modules/ngx-bootstrap/datepicker/bs-datepicker.css",
"src/styles.css"
],
"scripts": [
"./node_modules/alertifyjs/build/alertify.min.js"
]
}
I then run the application using dotnet run to serve the application on localhost:5000. The same day it all worked 100% and then after adding 2 components I am served with a blank page. I have removed the two components I added without having any effect. I still get a blank page with the console error messages as displayed in the image below.
Console error messages
For example, one of the error messages read "Failed to load resource: the server responded with a status of 400 (Bad Request)" and the file name is "main-es2015.9ddbf650cf0e7f09b565.js".
I have verified that the particular files exist at the path. I have also opened all the files and they all have contents in it. I copied the contents and verified (using an online validator) that the JavaScript in it is valid.
I also double-clicked on the file name as displayed in the console error and I am presented with the following .json formatted error message.
.json formatted error message
{
"errors": {
"dataanalysisId": [
"The value 'main-es2015.9ddbf650cf0e7f09b565.js' is not valid."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|82e44613-41a1b227ab4a5264."
}
What stands out to me is that One or more validation errors occurred and the The value 'main-es2015.9ddbf650cf0e7f09b565.js' is not valid.
What about "main-es2015.9ddbf650cf0e7f09b565.js" is not valid?
I also have double-checked the generated index.html file and the particular JavaScript file is referenced correctly.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Cache-Control" content="max-age=0, must-revalidate"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0" />
<title>TargetPro</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="/assets/images/NewBigenLogo.ico">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" rel="stylesheet">
<!-- <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="manifest" href="manifest.webmanifest">
<link rel="stylesheet" href="assets/custom.css">
<meta name="theme-color" content="#1976d2">
<link rel="stylesheet" href="styles.7a6852d4635a483ded1e.css">
</head>
<body class="body">
<app-root></app-root>
<!-- <noscript>Please enable JavaScript to continue using this application.</noscript> -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<script src="runtime-es2015.0dae8cbc97194c7caed4.js" type="module"></script>
<script src="runtime-es5.0dae8cbc97194c7caed4.js" nomodule defer></script>
<script src="polyfills-es5.177e85a9724683782539.js" nomodule defer></script>
<script src="polyfills-es2015.f332a089ad1600448873.js" type="module"></script>
<script src="scripts.e3f1622784b881f14c87.js" defer></script>
<script src="main-es2015.9ddbf650cf0e7f09b565.js" type="module"></script>
<script src="main-es5.9ddbf650cf0e7f09b565.js" nomodule defer></script>
</body>
</html>
I have also looked in the ngsw.json file to verify that the "main-es2015.9ddbf650cf0e7f09b565.js" file is included.
ngsw.json (extract)
{
"name": "app",
"installMode": "prefetch",
"updateMode": "prefetch",
"urls": [
"/favicon.ico",
"/index.html",
"/main-es2015.9ddbf650cf0e7f09b565.js",
"/main-es5.9ddbf650cf0e7f09b565.js",
"/manifest.webmanifest",
"/polyfills-es2015.f332a089ad1600448873.js",
"/polyfills-es5.177e85a9724683782539.js",
"/runtime-es2015.0dae8cbc97194c7caed4.js",
"/runtime-es5.0dae8cbc97194c7caed4.js",
"/scripts.e3f1622784b881f14c87.js",
"/styles.7a6852d4635a483ded1e.css"
],
"patterns": []
}
and
ngsw.json (extract)
"hashTable": {
"/assets/custom.css": "e81137cd383f52c600f10dabb84bd1484abc1181",
"/assets/icons/icon-128x128.png": "dae3b6ed49bdaf4327b92531d4b5b4a5d30c7532",
"/assets/icons/icon-144x144.png": "b0bd89982e08f9bd2b642928f5391915b74799a7",
"/assets/icons/icon-152x152.png": "7479a9477815dfd9668d60f8b3b2fba709b91310",
"/assets/icons/icon-192x192.png": "1abd80d431a237a853ce38147d8c63752f10933b",
"/assets/icons/icon-384x384.png": "329749cd6393768d3131ed6304c136b1ca05f2fd",
"/assets/icons/icon-512x512.png": "559d9c4318b45a1f2b10596bbb4c960fe521dbcc",
"/assets/icons/icon-72x72.png": "c457e56089a36952cd67156f9996bc4ce54a5ed9",
"/assets/icons/icon-96x96.png": "3914125a4b445bf111c5627875fc190f560daa41",
"/assets/images/NewBigenLogo.ico": "1971185fbe08c46b54eb2bb81d5232e8951084d3",
"/assets/images/TargetProLogo02.jpg": "df42312cbae197612480d8612796527459609d6d",
"/assets/images/TargetProLogo02Transparent.png": "52e5ec097ff8107d5bbacd8f28e3ed6c46c91911",
"/assets/images/bigen_horisontal_white_tagline.png": "9551491c578290df06600c6580c01bb21d71ade2",
"/fa-brands-400.1776173e3b1af55eb455.ttf": "29f59b4eecc72052d9110a5d4030a10ad9bf73d7",
"/fa-brands-400.28d8b8fcc41c3b7134ff.woff": "fddb95d7a0f48d2bf90a5ee3095e8264dca18053",
"/fa-brands-400.37913cdf7cb0571dfac0.woff2": "62584b9868428fd75af3fc5ee2f9918dda428be5",
"/fa-brands-400.63b566233f163d538cce.svg": "99dff0739882276ad6c434d73228efc7971b0a66",
"/fa-brands-400.bfcc3384b8a317dc5de3.eot": "40c8f2a0dc154160fde50e0c27f694f12c7b1636",
"/fa-regular-400.0c6f12b9eaa2ad444a6b.eot": "3306178c90d9df939d2a5eabf533ba3650fbe80e",
"/fa-regular-400.1b536b782d09dd59dda8.svg": "51afca56e309df6fdc56b53fa6a7d3ce64826490",
"/fa-regular-400.c3c2ab4f63b8d9973c78.woff2": "5e4d45052f43e55aaad7f14d13280215e39aa45b",
"/fa-regular-400.c9c57c0f1f4eb34dbf57.ttf": "517a3b41c1e01b65898b5f1074434d43a361a54f",
"/fa-regular-400.fcaa6c135683a3fa1b50.woff": "da17a9f1dcae379c8ba20f1089059c202216cba7",
"/fa-solid-900.22aa6d4357cf74671bc4.woff": "f13e252f8a51a5279fd21e26ada0bd2f55bcefd8",
"/fa-solid-900.3e2bc2ffd29f01066d23.svg": "5501fb62e20a89bdd89bf3fa147ca4dbcd2fc67f",
"/fa-solid-900.4055b0575d40bfb3c7e8.woff2": "6290834672aba86d5b6c1c73b30b57c9c53996f7",
"/fa-solid-900.a480ec972cb6bce30533.ttf": "874c650701d0cbfb8f1de48a496dabed3bbf22e6",
"/fa-solid-900.dfaa060a451d978c2565.eot": "96a5637429426764ea9b28bf4d1eb55ae10de57e",
"/favicon.ico": "22f6a4a3bcaafafb0254e0f2fa4ceb89e505e8b2",
"/index.html": "3097d526717744c5c5546bb7e6bd6d8c568b75c7",
"/main-es2015.9ddbf650cf0e7f09b565.js": "0fc7b0b2cc5f345d48a4b49d131facbc3129748d",
"/main-es5.9ddbf650cf0e7f09b565.js": "23296d15033f49a1cbe2dbc68423698d2d685c9b",
"/manifest.webmanifest": "2b9a2f8c92d7633e5cf15f0e60412ba827c7cb02",
"/polyfills-es2015.f332a089ad1600448873.js": "72ad4ccc0a3916ae4598199447cdeadd6d380570",
"/polyfills-es5.177e85a9724683782539.js": "8aa26ea87b9958c6bd13b7c257c0e9940438e684",
"/runtime-es2015.0dae8cbc97194c7caed4.js": "a9aafcf49f49145093fc831efd9b8e2f6c71bb9c",
"/runtime-es5.0dae8cbc97194c7caed4.js": "a9aafcf49f49145093fc831efd9b8e2f6c71bb9c",
"/scripts.e3f1622784b881f14c87.js": "e6b3c356e5949695046c95858db71a303e633dd1",
"/styles.7a6852d4635a483ded1e.css": "368e886c0e50a602803bedcee7c7bbb8c0583d5d"
}
I have included the headers below.
Headers
When I look at the headers of "main-es2015.9ddbf650cf0e7f09b565.js" request, I have noticed that the response headers return a application/problem+json; charset=utf-8 content type, which is not correct. The "main-es2015.9ddbf650cf0e7f09b565.js" file is a JavaScript file. My guess is that it has more to do with the return .json formatted error message than the JavaScript file itself.
I will appreciate any help and assistance. I think I am missing something that is glaringly obvious and it may have been starting right in the face. I have spent so much time trying to get to the bottom of this that I may be missing the obvious solution.
Edit - Solution
The solution for getting the application displayed was in the .NET Core startup.cs file. Thank you to Ronny for pointing me in the right direction.
In the Configure method I used app.UseEndpoints to include a mapping fallback to a controller which returns a PhysicalFile in wwwwroot called index.html. I commented this middleware out and ran dotnet run again and this time I was able to view the application as expected.
It is included in the startup.cs code extract of the Configure method below. It is the commented code.
startup.cs (extract)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (c, next) =>
{
if (c.Request.Path == "/")
{
c.Response.Headers.Add("Cache-Control", "no-store,no-cache");
c.Response.Headers.Add("Pragma", "no-cache");
}
await next();
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(builder =>
{
AllowedToAllowWildcardSubdomains();
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
// app.UseEndpoints(endpoints =>
// {
// endpoints.MapControllers();
// endpoints.MapFallbackToController("Index", "Fallback");
// });
}
It seems to me that the problem is that the .NET Core rounting is interfering with the angular routing. Its hard to tell because I dont know how you configured your startup, but try adding this middleware in the configure() method of the startup.cs file, after the authorization/authentication middlewares, and before the endpoints middleware:
app.MapWhen(
context =>
{
var path = context.Request.Path.Value.ToLower();
return path.Contains("/") &&
!path.Contains(".js") &&
!path.Contains("/api/") &&
!path.Contains("/assets") &&
!path.Contains(".ico");
},
branch =>
{
branch.Use((context, next) =>
{
context.Request.Path = new PathString("/index.html");
return next();
});
branch.UseStaticFiles();
});

Polymer novice, how to get require statement

I'm having trouble starting with polymer. The purpose is (simple) ; an Express server that serve my index.html and the index.html that serve my polymer element.
And my first problem is : How do I use node_moduldes and the require statement inside of my polymer element. I think I found some leads, like Browserify or RequireJS, but it seems complicated. (And browserify didnt work..).
Could someone provide me a simple way to use the node_modules in this polymer element ?
I'll start with my project structure.
And the file :
public/index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="import" href="./bower_components/webcomponentsjs/webcomponents-lite.js">
<link rel="import" href="./elements/neito-photoresistor.html">
<title>Neito's Domotics</title>
</head>
<styl></style>
<body>
<neito-photoresistor></neito-photoresistor>
</body>
</html>
server/app.js
"use strict"
//require
var express = require('express'),
path = require('path');
//Conf const
const _port = 3000;
//Server
var app = express();
//Middleware
app.use(express.static(path.join(__dirname, '/..', 'public')));
//Routing
app.get('/', function (req, res){
res.sendFile('../public/index.html', {root: __dirname});
})
.listen(_port, function (){
console.log('Server listening on : '+_port);
});
and the polymer element him self (I know it is complete bullshit but still the require problem is here): public/elements/neito-resistor.html :
<!DOCTYPE html>
<link rel="import" href="./../bower_components/polymer/polymer.html">
<!-- I know I cannot use the script src="" tag to import my node_modules -->
<dom-module id="neito-photoresistor">
<template>
<style>
</style>
<span>Ambient luminosity = <span>{{lum_pct}}</span> %</span>
</template>
<script>
Polymer({
is: 'neito-photoresistor',
ready: function() {
var mcp = require('mcp3008.js'),//I know that this line cause problem
can = new mcp();
},
properties: {
lum_pct: {
type: Number,
notify: true,
reflectToAttribute: true,
observer: '_getValueLumPct'
}
},
_getValueLumPct()
{
lum_pct = can.poll(0, 1000, function(value){
console.log('Luminosite ambiante = '+(100-((value/1024)*100))+' % ('+value+')');
return 100-((value/1024)*100);
});
}
});
</script>
</dom-module>

why jquery UI Widgets doesn't work in my laravel application?

I have laravel application and trying to use dialog widget, but I keep getting this error in the console:
TypeError: $(...).dialog is not a function[Learn More]
I tried to test normal jquery functions and it works fine, it is just jquery UI.
<head>
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- Scripts -->
<script>
window.Laravel = {!! json_encode([
'csrfToken' => csrf_token(),
]) !!};
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$( function() {
$( "#dialog" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
$( ".opener" ).on( "click", function() {
$( "#dialog" ).dialog( "open" );
});
} );
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
Update:
there is a conflict between these lines:
<script src="{{ asset('js/app.js') }}"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
but still can't remove any of them.
Update 2
webpack.mix.js
const { mix } = require('laravel-mix');
mix.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css');
app.js
require('./bootstrap');
window.Vue = require('vue');
Vue.component('example', require('./components/Example.vue'));
const app = new Vue({
el: '#app'
});
bootstrap.js
window._ = require('lodash');
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
See this link: https://github.com/JeffreyWay/laravel-mix/blob/master/docs/jquery-ui.md
NOTE: I am fairly new to Laravel Mix (webpack) and still learning.
In the linked example his resources/assets/js/app.js contains the lines:
import $ from 'jquery';
window.$ = window.jQuery = $;
but in my case I'm editing resources/assets/js/bootstrap.js, which contains the line:
window.$ = window.jQuery = require('jquery');
so I added the widget import line:
import 'jquery-ui/ui/widgets/dialog.js';
After the edits, to run the Mix tasks, I ran this command at my project root: npm run dev
And in my Chrome browser, on the page calling $(...).dialog(), I opened the devtools console and then right clicked on the browser page reload icon and clicked Empty cache and hard reload
Since I am using Laravel Mix (webpack) I do not need to include the jquery specific script tags and stylesheet links.
Are you using the .sass file that you're mixing in your webpack.mix.js file?
If not, try changing your webpack.mix.js to this:
const { mix } = require('laravel-mix');
mix.js('resources/assets/js/app.js', 'public/js');
New to Laravel and web development in general; that worked for me.
Try inserting app.js before jquery-ui.js. This makes jquery-ui.js overwrite any common code. I found it does not cause significant side-effects. Some items like tooltips will look different, but you can just modify the linked js files to handle that if necessary.

Why am I getting this Angular-Mock error and Mocha test is not running

I'm getting the exact error as found here: (window.beforeEach || window.setup) is not a function. However the fix did not work, the author of the tutorial series here even mentioned the same fix.
Here is the Tuts+ author's fix:
Which is simply to place the angular-mock script tag after the Mochai and Chai scripts. Which I did so below:
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>
<!-- see Angular-mocks is here :( -->
<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 runs our dashboard tests
*/
var assert = chai.assert;
var expect = chai.expect;
// This Test is designed to fail on purpose
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'
}
}
});
});
In your index.html file, you include the angular-mocks.js script before the call to mocha.setup('bdd'). angular-mocks.js is implemented as an immediately-invoked function expression which attempts to use window.beforeEach. (https://github.com/angular/bower-angular-mocks/blob/master/angular-mocks.js#L2586)
However, mocha.js is not immediately invoked and has to be initialized with the mocha.setup function in order to add its magic to the runtime environment.
Try reversing the order of these script tags, so that mocha.js is included 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>

Categories