简体   繁体   中英

How to run (Python-like) doctests in JavaScript?

Do any JavaScript test frameworks provide a rough equivalent to Python's doctest?

function add(a, b) {
  /**
  Returns the sum of `a` and `b`:

    > add(1, 3)
    4

  Add coerces types to numeric values where possible:

    > add('51' + 3)
    54
  */
  return (a - 0) + (b - 0);
}

I can't get the point of Ian Bicking's package, doctestjs. He just provides us a different way of writing normal external tests, not real doctests.

I use a lot python doctests, they are quite important for me, I don't know what doctestjs could be useful for, but I found some true doctests implemented with this project: https://github.com/davidchambers/doctest .

Even if that is not the most trendy doctest project for javascript, I strongly prefer it.


Update: after more that one year since this answer, i had the opportunity to contribute to the project from David Chambers, it is really well written. I also used it at work in a complex application using require.js , and for this we added support for AMD modules. I think he added support for Common JS modules as well. Thus i can only confirm my opinion.

Don't know what I was smoking yesterday. Soory.

doctestjs ( doctestjs on github ) is the correct link and it seems to be under active development too.

Although it works a little different from the python doctest in that with doctestjs you declare the tests in a HTML file so they can be run.

But I guess it should be possible to declare the test inline in your code. And then do a preprocessing step in your build process to extract the tests and automagically create a test-html from them

eg when using ant I imagine an applying copy file, replaceregexp, concat. eg copy the js file, replace everything which isn't a comment and all comments which don't look liks doctestjs tests. then concat htmlhead+tests+headfooter done.

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