简体   繁体   中英

helper functions in jasmine standalone

I have a Spec file unit testing a bunch of methods. In the same file I have helper functions. Is there a way to move the helper functions to a separate file with jasmine standalone and vanilla js?

  describe('#formatDateAndTime', () => {
    it('formats the date and time as per the requirements', () => {
      expect(till._formatDateAndTime()).toEqual(timeAndDate());
    });
  });

  function timeAndDate () {
    let today = new Date();
    return [today.getFullYear() + '.' + (today.getMonth() + 1) + '.' +
    today.getDate() + ' ' + today.getHours() + ':' + today.getMinutes() +
    ':' + today.getSeconds()];
  }

how can I move timeAndDate() function to a helper file

With Jasmine standalone, you link to all your scripts in an html file — let's call that tests.html. Let's say your test cases are in Tests.js, and you put your helpers in TestUtils.js.

Here's what you can do in that HTML file:

tests.html

 <html> <head> <title>Tests</title> <!-- Jasmine --> <link rel="shortcut icon" type="image/png" href="jasmine/lib/jasmine-3.3.0/jasmine_favicon.png"> <link rel="stylesheet" type="text/css" href="jasmine/lib/jasmine-3.3.0/jasmine.css"> <script type="text/javascript" src="jasmine/lib/jasmine-3.3.0/jasmine.js"></script> <script type="text/javascript" src="jasmine/lib/jasmine-3.3.0/jasmine-html.js"></script> <script type="text/javascript" src="jasmine/lib/jasmine-3.3.0/boot.js"></script> <!-- All scripts you want to test --> <script src='MyCoolProgram.js'></script> <!-- Specs --> <script src='TestUtils.js'></script> <script src='Tests.js'></script> </head> </html>

Then, simply open that file in a browser, and you should be able to see your tests running as required.

Careful! You must put TestUtils.js before Tests.js if you want Tests.js to call TestUtils.js helper methods. This is because in HTML, statically included scripts are injected in the order they appear in the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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