Category Archives: JavaScript

Testing with Jest: how to mock an import used by the module you’re testing

I am writing a Jest/RTL test for a React component that invokes another component. I want to mock that second component so I can have it do things like invoking callbacks that the first component passes to it.

But there is nothing specific to React about this requirement: it comes up for non-React modules, too. I have an approach that I have shown to work using trivial modules and I want to document it here for myself and anyone else who finds it useful.

Continue reading

React error-message of the day

This just in:

Failed context type: Invalid context `paneset` of type `Paneset` supplied to `Paneset`, expected instance of `Paneset`.

Oh, the joys of front-end development!

(My best guess: I have two slightly different version of stripes-components library that provides the <Paneset> component in my application, and somehow I’ve got hold of one from the wrong instance.)

Image

C++: the good parts

c++-the-good-parts

JavaScript hashes that inherit from a parent

For a JavaScript program I’m working on, I want to have hashes that can inherit values from a parent. Specifically, I have many widgets, each with a (usually small) hash of configuration parameters; when I access such a parameter and it’s not defined in the widget I want to get the value from the configuration of the team that the widget belongs to; and when that’s not defined I want it to get the value from the global configuration.

sushi-by-rob-owen-wahl-small

Continue reading

Why JavaScript is not my favourite programming language

Ahem.

Falsy Values

JavaScript has a surprisingly large set of falsy values, shown in Table A-1.

Value                Type
0                    Number
NaN (not a number)   Number
'' (empty string)    String
false                Boolean
null                 Object
undefined            Undefined

These values are all falsy [i.e. they test as false in conditionals], but they are not interchangeable.  For example, this is the wrong way to check if an object is missing a member:

   value = myObject[name];
   if (value == null) {
      alert(name + ' not found.");
   }

undefined is the value of missing members, but the snippet is testing for null.  It is using the == operator (See Appendix B), which does type coercion, instead of the more reliable === operator.  Sometimes these two errors cancel each other out.  Sometimes they don’t.

undefined and NaN are not constants.  They are global variables, and you can change their values.  That should not be possible, and yet it is.  Don’t do it.

– Douglas Crockford, JavaScript: The Good Parts, Appendix A: Awful Parts.

Case closed.