Jest encountered an unexpected token Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration. By default "node_modules" folder is ignored by transformers.
Conceptually, undefined indicates the absence of a value, while null indicates the absence of an object (which could also make up an excuse for [typeof null === "object"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null)). The language usually defaults to undefined when something is devoid of a value:
A [return](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return) statement with no value (return;) implicitly returns undefined.
Accessing a nonexistent object property (obj.iDontExist) returns undefined.
A variable declaration without initialization (let x;) implicitly initializes the variable to undefined.
Many methods, such as [Array.prototype.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) and [Map.prototype.get()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get), return undefined when no element is found.
null is used much less often in the core language. The most important place is the end of the prototype chain — subsequently, methods that interact with prototypes, such as [Object.getPrototypeOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf), [Object.create()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create), etc., accept or return null instead of undefined.
null is a keyword, but undefined is a normal identifier that happens to be a global property. In practice, the difference is minor, since undefined should not be redefined or shadowed.
undefined convert to other types
1 2 3
console.log(String(undefined)); // "undefined" console.log(Number(undefined)); // NaN console.log(Boolean(undefined)); // false
Posted onEdited onInjavascript Symbols count in article: 288Reading time ≈1 mins.
Optional chaining
Why optional chaining
Have you write the following code before?
1 2 3
if (user && user.address && user.address.street) { console.log(user.address.street); }
With optional chaining operator, you don’t need so many && to get a deeply nested property.
1
console.log(user?.address?.street);
How to use optional chaining
The optional chaining (?.) operator accesses an object’s property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
Access object’s property
1 2 3 4 5 6
const person = { name: 'Philip', };
console.log(person.info.address); // TypeError: Cannot read property 'address' of undefined.(Because, person does not have property 'info') console.log(person.info?.address); // undefined
Call a function
1 2 3 4 5 6 7 8 9 10
functiondoSomething(onContent, onError) { try { // Do something with the data } catch (err) { // Testing if onError really exists if (onError) { onError(err.message); } } }
With optional chaining, you don’t need too check weather onError is defined or not.
1 2 3 4 5 6 7
functiondoSomething(onContent, onError) { try { // Do something with the data } catch (err) { onError?.(err.message); // No exception if onError is undefined } }
Short circuit
When using optional chaining, if the left operand is null or undefined, the expression will not be evaluated, for instance:
1 2 3 4 5
let i = 0; const nums = null; const firstNumber = nums?.[i++]; console.log(x); // 0, since num?. trigger short circuit, [i++] is not evaluated.
?. not work for non-declared root object
Optional chaining can not be used with a non-declared root object, but can be used with a root object that is null or undefined.
1 2 3
console.log(a?.b); // Uncaught ReferenceError: a is not defined console.log(null?.b); // undefined console.log(undefined?.b); // undefined
In javascript, not defined and undefined are two different concepts. See undefined vs not defined
Posted onEdited onInjavascript Symbols count in article: 121Reading time ≈1 mins.
undefined vs not defined
In JavaScript, undefined and not defined are two different concepts.
undefined: a variable has been declared but has not yet been assigned a value.
not defined: a variable has not been declared(not exists).
undefined
1 2
let a; console.log(a); // undefined
not defined
1
console.log(b); // Uncaught ReferenceError: b is not defined
Whenever you try to access a variable that is not declared, JavaScript throws an error: Uncaught ReferenceError: xxx is not defined. This is because variable b is not declared anywhere in the code. but you can still use typeof to check if a variable is defined or not.
typeof
1 2 3
let a; console.log(typeof a); // undefined console.log(typeof b); // undefined, even b is not defined
Limitation: The fakeAsync() function won’t work if the test body makes an XMLHttpRequest (XHR) call. XHR calls within a test are rare, but if you need to call XHR, see the waitForAsync() section.
it('should show quote after getQuote (waitForAsync)', waitForAsync(() => { fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).withContext('should show placeholder').toBe('...');
fixture.whenStable().then(() => { // wait for async getQuote fixture.detectChanges(); // update view with quote expect(quoteEl.textContent).toBe(testQuote); expect(errorMessage()).withContext('should not show error').toBeNull(); }); }));
// This object is the return value of init will be assigned to instance. return { // Public methods and variables publicVariable: 'I am public variable', publicMethod: () => { console.log('Public method'); }, }; };
// Public method to get the singleton instance constgetInstance = () => { if (!instance) { instance = init(); } return instance; };
// Expose the public method return { getInstance, }; })();
functioncreateInstance(name) { if (!instance) { // Init code goes here, If you want to exact init to a function, you must use createInstance.prototype.init = function(name){this.name = name}. This will make init public to every instance, it's bad idea! this.name = name; instance = this; }
return instance; }
return createInstance; })();
const a = newSingleton('zdd'); const b = newSingleton('ddz'); console.log(a === b); // true
下面是使用ES6的class来实现单例模式。代码更加简洁优雅。
Use class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSingleton { constructor() { if (!Singleton.instance) { Singleton.instance = this; // Your initialization code here } returnSingleton.instance; }
// Additional properties and methods can be added here }
In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.