How to test this statement using jest and enzyme - javascript

In our code, I have two statements
const { column, showTooltip, tooltipValue, data } = props;
const key = column.bindProperties[0].properties[0].name;
on testing, this gives error as
"TypeError: Cannot read property '0' of undefined."
what is the meaning of this statement column.bindProperties[0].properties[0].name; and how to test it.

In JS you can't guarantee that objects have certain properties.
When you try to access column.bindProperties[0].properties[0].name, either column.bindProperties or column.bindProperties[0].properties is undefined - hence the error you're getting.
You can either use lodash's _.get() or validate the keys are defined using the redundantly annoying:
const key = column
&& column.bindProperties
&& column.bindProperties[0]
&& column.bindProperties[0].properties
&& column.bindProperties[0].properties[0]
&& column.bindProperties[0].properties[0].name;
This will make sure your code won't break. If one expression in the chain isn't defined, the expression will stop evaluating and you'll just get undefined as the result.

Since no one has really just spelt it out, here's an example of optional chaining:
const key = column?.bindProperties?.[0]?.properties?.[0]?.name;
and with nullish coalescing:
const key = column?.bindProperties?.[0]?.properties?.[0]?.name ?? "I'm a fallback value";

Related

Object is possibly 'undefined' Error on Optional Chaining Typescript

I have a response which I am accessing: data?.currentOrganization?.onboardingSteps?. As you can guess, data, currentOrganization, and onboardingSteps might all be null. I want to assign a variable as follows:
const hasSteps = data?.currentOrganization?.onboardingSteps?.length > 0;
I thought hasValue would evaluate to false if any of the fields were null or if there was less than 1 step. However, I get the TypeScript error: Object is possibly 'undefined'.
This is how I am currently getting around it:
const hasSteps =
data?.currentOrganization?.onboardingSteps != null &&
data?.currentOrganization?.onboardingSteps?.length > 0;
This feels unnecessarily verbose. Is there an alternative, more elegant solution?
The optional chain will end up producing a value for data?.currentOrganization?.onboardingSteps?.length which is presumably a number if everything in the chain is not null or undefined.... but if anything in the chain is nullish, then the output will be undefined itself. You can't test undefined > 0 without Typescript complaining about it.
So you should probably do something like the following:
const hasSteps = (data?.currentOrganization?.onboardingSteps?.length ?? 0) > 0;
This is using nullish coalescing to produce 0 if the optional chain ends in undefined.
Playground link to code

How can I use optional chaining with arrays and functions?

I'm trying to use optional chaining with an array instead of an object but not sure how to do that:
Here's what I'm trying to do myArray.filter(x => x.testKey === myTestKey)?[0].
Also trying similar thing with a function:
let x = {a: () => {}, b: null}
console.log(x?b());
But it's giving a similar error - how can I use optional chaining with an array or a function?
You need to put a . after the ? to use optional chaining:
myArray.filter(x => x.testKey === myTestKey)?.[0]
Playground link
Using just the ? alone makes the compiler think you're trying to use the conditional operator (and then it throws an error since it doesn't see a : later)
Optional chaining isn't just a TypeScript thing - it is a finished proposal in plain JavaScript too.
It can be used with bracket notation like above, but it can also be used with dot notation property access:
const obj = {
prop2: {
nested2: 'val2'
}
};
console.log(
obj.prop1?.nested1,
obj.prop2?.nested2
);
And with function calls:
const obj = {
fn2: () => console.log('fn2 running')
};
obj.fn1?.();
obj.fn2?.();
Just found it after a little searching on the what's new page on official documentation
The right way to do it with array is to add . after ?
so it'll be like
myArray.filter(x => x.testKey === myTestKey)?.[0]
I'll like to throw some more light on what exactly happens with my above question case.
myArray.filter(x => x.testKey === myTestKey)?[0]
Transpiles to
const result = myArray.filter(x => x.testKey === myTestKey) ? [0] : ;
Due to which it throws the error since there's something missing after : and you probably don't want your code to be transpilled to this.
Thanks to Certain Performance's answer I learned new things about typescript especially the tool https://www.typescriptlang.org/play/index.html .
ECMA 262 (2020) which I am testing on Edge Chromium 84 can execute the Optional Chaining operator without TypeScript transpiler:
// All result are undefined
const a = {};
console.log(a?.b);
console.log(a?.["b-foo-1"]);
console.log(a?.b?.());
// Note that the following statements throw exceptions:
a?.(); // TypeError: a is not a function
a?.b(); // TypeError: a?.b is not a function
CanIUse: Chrome 80+, Firefox 74+
After a bit of searching the new page in the official documentation, it was discovered.
You need to put a . after the ? to use optional chaining.
So it will be so,
myArray.filter(x => x.testKey === myTestKey)?.[0]
Used only ? Makes the compiler think that you are trying to use a conditional operator (then it causes an error because it doesn't see a : later)
It's not necessary that the function is inside the object, you can run a function using optional chaining also like this:
someFunction?.();
If someFunction exists it will run, otherwise it will skip the execution and it will not error.
This technique actually is very useful especially if you work with reusable components and some components might not have this function.
Well, even though we figured out the correct syntax, the code doesn't make much sense to me.
The optional chaining in the code above is making sure, that the result of myArray.filter(x => x.testKey === myTestKey) is not null and not undefined (you can have a look at the TS output). But it is not possible anyway, because the result of the filter method is always an array. Since JavaScript doesn't throw "Array bounds exceeded", you are always safe when you try to access any index - you will get undefined if this element doesn't exist.
More example to make it clear:
const myArray: string[] = undefined
console.log(myArray.filter(x => x)?.[0]) //throws Cannot read property 'filter' of undefined
//in this example the optional chaining protects us from undefined array
const myArray: string[] = undefined
console.log(myArray?.filter(x => x)[0]) //outputs "undefined"

TS2532: Object is possibly 'undefined'. on array.map()

I understand that this TS error is essentially just a warning but I have been unable to find a solution when it occurs on .map
const files = require.context("./", true, /\.vue$/i);
files.keys().map(key =>
Vue.component(
key
.split("/")
.pop()
.split(".")[0],
files(key).default
)
);
I have tried checking if the value of key exists before doing anything else but it still produces the same error.
TS2532: Object is possibly 'undefined'.
You are trying to split a string. Using someString.split("/"), which does return an array. Using the method pop() does either return the last element of the array or undefined (according to MDN)
Therefore your typing at that point is: string | undefined executing .split(..) on an undefined value will cause problems. That's what TypeScript is trying to tell you here.
To avoid this warning/error and to be type safe you could use the latest optional chaining feature TypeScript 3.7.0 provides you if applicable:
key.split("/").pop()?.split(".")[0] ?? someDefaultString
An alternative solution would be to extract this kind of logic into another function like so:
function extractValue(key: string): string { // you want to name that function better though
return key.split("/").pop()?.split(".")[0] ?? "defaultValue";
}
And use it like:
Vue.component(extractValue(key), files(key).default)

Typescript 3.7#beta Optional Chaining operator using problem

I'm trying to use the Typescript optional chaining operator but it threw this exception:
index.ts:6:1 - error TS2779: The left-hand side of an assignment
expression may not be an optional property access.
My sample code:
const url = URI({
protocol: 'http',
hostname: 'example.org'
})
// This line threw
document.getElementById('output')?.innerHTML = url.toString()
How to resolve this problem?
objectVariableName!.propertyName = 'some value to assign';
Please note the exclamation symbol i.e,!
const output = document.getElementById('output');
if (output) output.innerHTML = url.toString()
This operator is made for accessing deep nest values.
Let's look at document.getElementById('output')?.innerHTML. This will return undefined (if '#output' not exists) or string (if '#output' exists). And you trying to assign string to it.
Here you are trying to set a new value for an object property that may not exist.
So yep, optional property access can not be used at the left-hand side of an assignment.
You can read more about it in proposal
You can also solve this with an early return:
const output = document.getElementById('output');
if (!output) return;
output.innerHTML = url.toString()
Use it like this for nested properties:
if (!item?.text) return;
item.text.text = action.payload.text;
https://medium.com/swlh/return-early-pattern-3d18a41bba8
https://softwareengineering.stackexchange.com/questions/18454/should-i-return-from-a-function-early-or-use-an-if-statement
As mentioned here:
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string.
If we go and see what properties the Element base class contains, you will see innerHTML.
This means that it is sure that an instance of Element(the result of getElementById) will have an innerHTML property, which is why you're getting the error.
This very short expression works for me nicely in typescript 4.0.3
let domEl: HTMLElement | null = document.querySelector("#app");
domEl && (domEl.style.color = "green");
in ES12 you can do this with Logical nullish assignment
document.getElementById('output')?.innerHTML ??= url.toString()
so the assignment will happen only if the left-hand expression is not nullish.
this is just like if you would do
if (document.getElementById('output')?.innerHTML) {
document.getElementById('output').innerHTML = url.toString()
}
My exception was :
The left-hand side of an assignment expression may not be optional property access.
I received this error in typescript "~4.6.2" and solved it like.
let headingDom : HTMLElement | null = document?.querySelector('h1');
if(headingDom) headingDom.textContent = 'Hello World';

Automated testing with chai js

I want to load a configuration file for tests.
One of the parameters is type.
So how can I replace the next line.
expect(res.body).to.deep.equal(test.expect)
with "to.deep.equal" string.
I tried :
let exp = expect(res.body);
test.type.split('.').forEach(t => exp = exp[t])
exp(test.expect)
But then i got:
Uncaught TypeError: this.assert is not a function
at assertEqual (node_modules\chai\lib\chai\core\assertions.js:1026:12)
EDIT:
I managed to do it in the following way:
let exp = expect(res.body);
test.type.split('.').slice(0,-1).forEach(t => exp = exp[t])
exp[_.last(test.type.split('.'))](test.expect)
I'd love to get an explanation for that. and if is exist another way for it.
Because you're breaking the thisValue of the last member (equal), which it tries to access but is no longer bound to deep object.
(I'm really butchering the explanation).
You can do:
let exp = expect(res.body);
test.type.split('.').forEach(t => {
exp = typeof exp[t] === 'function'
? exp[t].bind(exp)
: exp[t];
});
exp(test.expect)
To further explain, this is why you're seeing the TypeError: this.assert is not a function - the equal call is trying to access this.assert of the deep object, but the this is no longer bound to it. By explicitly binding it via .bind() we can retain it.
That's also why your second code example works, because you're properly calling the equal() as a method of deep.

Categories

Resources