简体   繁体   English

如何以允许在网站中使用的方式对我的 JavaScript 代码进行单元测试?

[英]How can I unit test my JavaScript code in a way that allows it to be used in a website?

I have built a web app and I am trying to build out an automated unit testing suite so that I can more easily refactor the code.我已经构建了一个 web 应用程序,并且我正在尝试构建一个自动化单元测试套件,以便我可以更轻松地重构代码。

I have javascript code that functions correctly on my website.我有在我的网站上正常运行的 javascript 代码。 Simple hypothetical code:简单的假设代码:

function timesTwo(x){x*=2;return x}

If I were writing my code for NodeJS I would add the tests to confirm that the code is working correctly.如果我正在为 NodeJS 编写代码,我会添加测试以确认代码正常工作。 Below is an example using Wish and Mocha:下面是一个使用 Wish 和 Mocha 的示例:

describe('timesTwo()', function() {
  it('multiplies by two', function() {
    var result = timesTwo(5);
    wish(result === 10);
  });
});

This code (including tests) works fine if I run it in node.JS to test it, but now it throws errors in my browser:如果我在 node.JS 中运行此代码(包括测试)来测试它,它可以正常工作,但现在它会在我的浏览器中引发错误:

require is not defined

describe is not defined

wish is not defined

How can I create an automated test suite for my code in a way that doesn't throw errors in the browser?如何以不会在浏览器中引发错误的方式为我的代码创建自动化测试套件?

If I'm not mistaken you're also loading the test code into your browser.如果我没记错的话,您还将测试代码加载到浏览器中。

The thing is that require isn't something that's available in your browser.问题是require不是您的浏览器中可用的东西。 This means that the functions like describe and wish are simply not available since the require didn't include any code.这意味着describewish等函数根本不可用,因为require不包含任何代码。

What you should do is keep the tests separate from your application code and only load the application code into your website.您应该做的是将测试与您的应用程序代码分开,并且只将应用程序代码加载到您的网站中。 How you do this depends on your build system, template engine, etc你如何做到这一点取决于你的构建系统、模板引擎等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM