gpt4 book ai didi

javascript - 通过 Jasmine 测试 JavaScript 文件

转载 作者:行者123 更新时间:2023-11-29 21:45:10 25 4
gpt4 key购买 nike

我正在尝试学习如何使用 Jasmine 对 JavaScript 文件进行单元测试。此时,我有以下内容

/dist/MyJavaScriptFile.min.js

function MyClass() {}
module.exports = MyClass;

MyClass.prototype.test = function(msg) {
console.log(msg);
};

我想用 Jasmine 测试这个类中的函数。为了做到这一点,我有以下内容:

/test/unit/MyJavaScriptFile.spec.js

describe('MyClass', function() {
beforeEach(function() {
module('MyClass');
});

describe('Test', function () {
it('should write a message', function() {
MyClass.test('hello from the test.');
});
});
});

当我尝试从 Gulp 运行这些测试时,出现错误。错误是:

Failures: 
1) MyClass Test should write a message
1.1) TypeError: object is not a function

我相信这是因为 /dist/MyJavaScriptFile.min.jsMyClass 没有作为依赖加载。我以为我是用 module('MyClass'); 行来做的。但是,我看不出 .spec.js 文件或 Jasmine 测试运行器如何知道 MyClass 定义的位置。我做错了什么?

最佳答案

为了使用 gulp-jasmine 进行测试,我已经包含了我的 js 代码,使用类似这样的东西来测试我的规范:

// Path is relative to specs location
var someLibToTest = require('path/to/my/js/file');

至于你在这里使用commonjs模块语法,你可以用同样的方式来做。但这仅适用于控制台测试,不适用于浏览器。

关于javascript - 通过 Jasmine 测试 JavaScript 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31477913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com