Should js Cannot read property 'should' of null

独自空忆成欢 提交于 2019-12-03 09:25:56

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.

Henry Tao

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

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

You can use should directly

should.not.exist(err);

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
Jeff C

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

expect(err).be.null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!