为什么我得到这个Angular-Mock错误并且Mocha测试没有运行

时间:2016-02-17 15:41:14

标签: javascript angularjs mocha chai angular-mock

我收到了确切错误(window.beforeEach || window.setup) is not a function。但是修复无法正常工作author of the tutorial series here甚至提到了相同的修复方法。

以下是Tuts +作者的修复: enter image description here

只需将angular-mock脚本标记放在MochaiChai脚本之后。我在下面这样做了:

enter image description here

测试/ 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>

我的main.spec.js文件

/**
 * @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');
        });
    });    
});

我的Gulp任务

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'
            }
        }
    });
});

1 个答案:

答案 0 :(得分:2)

index.html文件中,您在<{1}}之前调用angular-mocks.js脚本mocha.setup('bdd')实现为立即调用的函数表达式,尝试使用angular-mocks.js。 (https://github.com/angular/bower-angular-mocks/blob/master/angular-mocks.js#L2586

但是,window.beforeEach不会立即被调用,必须使用mocha.js函数进行初始化,以便将其魔力添加到运行时环境中。

尝试颠倒这些脚本代码的顺序,以便在mocha.setup之前包含mocha.js并进行初始化。

angular-mocks.js