Should js Cannot read property 'should' of null

前端 未结 5 1627
执念已碎
执念已碎 2021-02-06 23:35

i try to use the testing tool mocha in node. Consider the following test scenario

var requirejs = require(\'requirejs\');

requirejs.config({
    //Pass the top-         


        
5条回答
  •  -上瘾入骨i
    2021-02-06 23:51

    That's a known problem with the should library: As it extends object, of course it only works when you have a concrete object. As null, by definition, means that you don't have an object, you can not call any methods on it or access any of its properties.

    Hence, should is not available in this case.

    Basically, you have two options of how to deal with this:

    1. You could exchange actual and expected. This way, as long as you do not expect null, you have an object in the beginning and hence can access its should property. But, this is not nice, as it changes semantics, and does not work in all cases.
    2. You could exchange the should library by another assertion library that does not have this problem.

    Personally, I'd go with option 2, and my highly subjective personal favorite for this is node-assertthat (which has been written by me, hence it's my favorite).

    Anyway, there are lots of other options, such as expect. Feel free to use any of these assertion libraries that best suits your style of writing tests.

提交回复
热议问题