Should js Cannot read property 'should' of null

前端 未结 5 1631
执念已碎
执念已碎 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条回答
  • 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.

    0 讨论(0)
  • 2021-02-07 00:00

    One more option that I don't see mentioned here:

    should(err === null).be.null
    

    In you example that would would be:

    should(accountExists).be.null
    
    0 讨论(0)
  • 2021-02-07 00:12

    I always find expect works better with null and undefined as follows:

    expect(err).be.null

    0 讨论(0)
  • 2021-02-07 00:17

    You can use should directly

    should.not.exist(err);
    
    0 讨论(0)
  • 2021-02-07 00:18

    I had the same problem. I solved it by using:

    (err === null).should.be.true;

    0 讨论(0)
提交回复
热议问题