Sometimes when I update the snapshots I got an Attribute __ngContext__ - jestjs

Sometimes when I update the snapshots I got an Attribute ngContext and for fix this problem I've to clean and install my node_modules to "fix" this issue.
I've to do this every time that I need to update a snapshot. I've already searched on multiple solutions and nothing worked.
snapshotSerializers: \[
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
\],
Can someone help me with this, please?
Here is an image
I've updated the jest versions and also the jest-present-angular too but didn't work.
I just want to have a solution that does not makes me clean install the node_modules every time

This is indeed annoying especially because it tends to change after upgrading angular version. My snapshots are now failing as well because of this difference :-/.
- __ngContext__={[Function LRootView]}
+ __ngContext__="0"
So, having look at the jest configuration, the snapshot serializers are being loaded from 'jest-preset-angular' module.
The relevant plugin here is 'jest-preset-angular/build/serializers/ng-snapshot'. Now, they are two ways what to do to get rid of __ngContext__.
replace the plugin entirely by a modified copy
Create a copy of that file in the same directory and adapt it accordingly (line https://github.com/thymikee/jest-preset-angular/blob/40b769b8eba0b82913827793b6d9fe06d41808d9/src/serializers/ng-snapshot.ts#L69):
const attributes = Object.keys(componentInstance).filter(key => key !== '__ngContext__');
Adapt the configuration:
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'./custom-snapshot-serializer.ts',
'jest-preset-angular/build/serializers/html-comment',
],
The disadvantage of this solution is that you have to maintain the plugin although only one line has been changed.
replace the plugin by a wrapper (preferred solution)
This creates just a wrapper for the original implementation. The idea is to remove __ngContext__ before it moves on down the plugin chain. However, the logic of the original plugin is used for the fixture serialization.
import type { ComponentRef, DebugNode, Type, ɵCssSelectorList } from '#angular/core';
import type { ComponentFixture } from '#angular/core/testing';
import type { Colors } from 'pretty-format';
import { test as origTest, print as origPrint } from 'jest-preset-angular/build/serializers/ng-snapshot';
/**
* The follow interfaces are customized heavily inspired by #angular/core/core.d.ts
*/
interface ComponentDef {
selectors: ɵCssSelectorList;
}
interface IvyComponentType extends Type<unknown> {
ɵcmp: ComponentDef;
}
interface NgComponentRef extends ComponentRef<unknown> {
componentType: IvyComponentType;
_elDef: any; // eslint-disable-line #typescript-eslint/no-explicit-any
_view: any; // eslint-disable-line #typescript-eslint/no-explicit-any
}
interface NgComponentFixture extends ComponentFixture<unknown> {
componentRef: NgComponentRef;
// eslint-disable-next-line #typescript-eslint/no-explicit-any
componentInstance: Record<string, any>;
}
/**
* The following types haven't been exported by jest so temporarily we copy typings from 'pretty-format'
*/
interface PluginOptions {
edgeSpacing: string;
min: boolean;
spacing: string;
}
type Indent = (indentSpaces: string) => string;
type Printer = (elementToSerialize: unknown) => string;
export const print = (fixture: any, print: Printer, indent: Indent, opts: PluginOptions, colors: Colors): any => {
const componentInstance = (fixture as NgComponentFixture).componentInstance;
const instance = { ...componentInstance };
delete instance.__ngContext__;
const modifiedFixture = { ...fixture, componentInstance: { ...instance } };
return origPrint(modifiedFixture, print, indent, opts, colors);
};
// eslint-disable-next-line #typescript-eslint/no-explicit-any, #typescript-eslint/explicit-module-boundary-types
export const test = (val: any): boolean => {
return origTest(val);
};
The configuration is adapted the same way as before.

Related

How to clear undo history in CodeMirror 6?

editor.clearHistory(); works in CodeMirror 5 I believe, but what about CodeMirror 6?
interface HistoryConfig {
/**
The minimum depth (amount of events) to store. Defaults to 100.
*/
minDepth?: number;
/**
The maximum time (in milliseconds) that adjacent events can be
apart and still be grouped together. Defaults to 500.
*/
newGroupDelay?: number;
}
/**
Create a history extension with the given configuration.
*/
declare function history(config?: HistoryConfig): Extension;
import { EditorView } from '#codemirror/view';
import { EditorState } from '#codemirror/state';
import { history } from '#codemirror/commands';
const state = EditorState.create({
doc: 'my source code',
extensions: [history({ minDepth: 10 })],
});
const view = new EditorView({
parent: document.querySelector('#editor'),
state,
});

How to read properties in typescript after using Object.defineProperty?

I have the following code on typescript playground and a few questions come up that I am not sure how to get working
class PathInfo {
functionName: string;
httpPath: string;
httpMethod: string;
constructor(functionName: string, httpPath: string, httpMethod: string) {
this.functionName = functionName;
this.httpPath = httpPath;
this.httpMethod = httpMethod;
}
toString(): string {
return "PathInfo["+this.functionName+","+this.httpPath+","+this.httpMethod+"]";
}
}
class AuthRequest {}
class AuthResponse {}
class LoginRequest {}
class LoginResponse {}
const path: any = (thePath: string, type: any) => {
return (target: Function, memberName: string, propertyDescriptor: PropertyDescriptor) => {
const pathMeta = new PathInfo(memberName, path, type);
Object.defineProperty(target, memberName+'pathInfo', {
value: pathMeta,
writable: false
});
//How do I access the stored pathMeta
//console.log("target="+target.pathInfo);
console.log("member="+memberName);
console.log("props="+propertyDescriptor);
}
}
class AuthApiImpl {
#path("/authenticate", AuthResponse)
authenticate(request: AuthRequest): Promise<AuthResponse> {
throw new Error("all this is generated by factory.createApiImpl");
}
#path("/login", LoginResponse)
login(request: LoginRequest): Promise<LoginResponse> {
throw new Error("all this is generated by factory.createApiImpl");
}
};
function printMethods(obj: any) {
console.log("starting to print methods");
for (var id in obj) {
console.log("id="+id);
try {
//How do I access the stored pathMeta here FOR EACH METHOD ->
//console.log("target="+target.pathInfo);
if (typeof(obj[id]) == "function") {
console.log(id+":"+obj[id].toString());
}
} catch (err) {
console.log(id + ": inaccessible"+err);
}
}
}
console.log("starting to run")
const temp = new AuthApiImpl();
printMethods(temp);
console.log("done")
line 64-65, how to read the property that I set
line 40-41, how to read the property that I set
line 58-74, why is this not printing any functions? I want to print all functions and I do NOT want to print properties (just functions)
line 33, Can I access the class name at this point?
line 35, I thought target was a function and would be authorize, then login, BUT if I define the property as JUST 'pathInfo', I get an error that the property is already defined on the target(This implies the target is the class not the function?). I am so confused.
Terribly sorry as I try to focus on a single question, but this one test of writing decorators has given me more questions than answers as I delve into the typescript world.
How can I tweak the code to play more here?
A goal here is as developers define the APIs of other microservices, I can capture a bunch of meta information and store it SOMEWHERE I can use later in startup code. I do not care where I store that really, but just need a clean way of knowing the class I want to extend, the methods, the return types, the http path, etc.
How to get methods of a class
You still can't grab the method names even if you remove the decorator. This isn't a TypeScript specific question.
You need to get the properties of the prototype, not just the object itself.
function printMethods(obj: any) {
console.log("starting to print methods");
const objProto = Object.getPrototypeOf(obj);
console.log(Object.getOwnPropertyNames(objProto));
}
How to access class names
Don't think this is possible with decorators at the moment, but it should be straightforward to just pass in your class name as a string.
Similar issue: TypeScript class decorator get class name
Open issue on GitHub: https://github.com/microsoft/TypeScript/issues/1579
"property is already defined on the target"
Notice if you run the code above you get the following in console.log:
["constructor", "authenticate", "login", "authenticatepathInfo", "loginpathInfo"]
I also want to point out that if you don't even initialize an instance of the class, you'll still get the same error.
I want to read this meta data in nodejs and use that to dynamically create a client implementing the api. Basically, developers never have to write clients and only write the api and the implementation is generated for them.
If I were to do that, I'd probably not use decorators, but mapped types:
// library code
interface ApiMethodInfo {
httpPath: string;
httpMethod: string;
}
type ApiInfo<S extends object> = Record<keyof S, ApiMethodInfo>;
type Client<S extends object> = {[key in keyof S]: S[key] extends (req: infer Req) => infer Res ? (req: Req) => Promise<Res> : never};
function generateClient<S extends object>(apiInfo: ApiInfo<S>): Client<S> {
const client = {} as Client<S>;
for (const key in apiInfo) {
const info = apiInfo[key as keyof S];
client[key] = ((param: any) => invokeApi(info, param)) as any;
}
return client;
}
// application code
interface AuthRequest {}
interface AuthResponse {}
interface LoginRequest {
username: string,
password: string,
}
interface LoginResponse {}
interface MyServer {
authenticate(request: AuthRequest): AuthResponse;
login(request: LoginRequest): LoginResponse;
}
const myApiInfo: ApiInfo<MyServer> = { // compiler verifies that all methods of MyServer are described here
authenticate: {
httpPath: '/authenticate',
httpMethod: 'POST'
},
login: {
httpPath: '/login',
httpMethod: 'POST'
}
}
const myClient = generateClient(myApiInfo); // compiler derives the method signatures from the server implementation
const username = "joe";
const password = "secret";
const response = myClient.login({username, password}); // ... and can therefore check that this call is properly typed
(To understand how these type definitions work, you may want to read the section Creating Types from Types in the TypeScript Handbook)
The weakness of this approach is that while the compiler can derive the client signatures from the server signatures, it will not copy any JSDoc, so client devs can not easily access the API documentation.
In the above code, I chose to specify the metadata in a separate object rather than decorators so the compiler can check exhaustiveness (decorators are always optional; the compiler can not be instructed to require their presence), and because decorators are an experimental language feature that may still change in future releases of the language.
It is entirely possible to populate such a metadata object using decorators if that's what you prefer. Here's what that would look like:
// library code
interface ApiMethodInfo {
httpPath: string;
httpMethod: string;
}
const apiMethodInfo = Symbol("apiMethodInfo");
function api(info: ApiMethodInfo) {
return function (target: any, propertyKey: string) {
target[apiMethodInfo] = target[apiMethodInfo] || {};
target[apiMethodInfo][propertyKey] = info;
}
}
type ApiInfo<S extends object> = Record<keyof S, ApiMethodInfo>;
type Client<S extends object> = {[key in keyof S]: S[key] extends (req: infer Req) => infer Res ? (req: Req) => Promise<Res> : never};
function invokeApi(info: ApiMethodInfo, param: any) {
console.log(info, param);
}
function generateClient<S extends object>(serverClass: new() => S): Client<S> {
const infos = serverClass.prototype[apiMethodInfo]; // a decorator's target is the constructor function's prototype
const client = {} as Client<S>;
for (const key in infos) { // won't encounter apiMethodInfo because Symbol properties are not enumerable
const info = infos[key];
client[key as keyof S] = ((param: any) => invokeApi(info, param)) as any;
}
return client;
}
// application code
interface AuthRequest {}
interface AuthResponse {}
interface LoginRequest {
username: string,
password: string,
}
interface LoginResponse {}
class MyServer {
#api({
httpPath: '/authenticate',
httpMethod: 'POST'
})
authenticate(request: AuthRequest): AuthResponse {
throw new Error("Not implemented yet");
}
#api({
httpPath: '/login',
httpMethod: 'POST'
})
login(request: LoginRequest): LoginResponse {
throw new Error("Not implemented yet");
}
}
const myClient = generateClient(MyServer); // compiler derives the method signatures from the server implementation
const username = "joe";
const password = "secret";
const response = myClient.login({username, password}); // ... and can therefore check that this call is properly typed
Notice how using a Symbol prevents name collisions, and ensures that other code doesn't see this property (unless they look for that particular Symbol), and therefore can not be tripped up by its unexpected presence.
Also notice how MyServer, at runtime, contains the constructor of the class, whose prototype holds the declared instance methods, and it being passed as target to any decorators thereof.
General Advice
May I conclude with some advice for the recovering Java programmer? ;-)
EcmaScript is not Java. While the syntax may look similar, EcmaScript has many useful features Java does not, which often allow writing far less code. For instance, if you need a DTO, it is wholly unnecessary to declare a class with a constructor manually copying each parameter into a property. You can simply declare an interface instead, and create the object using an object literal. I recommend looking through the Modern JavaScript Tutorial to familiarize yourself with these useful language features.
Also, some features behave differently in EcmaScript. In particular, the distinction between class and interface is quite different: Classes are for inheriting methods from a prototype, interfaces for passing data around. It's quite nonsensical to declare a class for a Response that will be deserialized from JSON, because prototypes don't survive serialization.

NestJS/Express: Case-Insensitive Body Fields

I'm struggling to make the fields of my request DTOs case insensitive.
export class ExampleDto {
dateOfBirth?: string
}
Now I want to accept
{ "dateofbirth": "19880101" }
{ "dateOfBirth": "19880101" }
{ "DATEOFBIRTH": "19880101" }
My first thought was to implement a middleware which just looks at the incoming body and "extends it" with lower & upper case mappings for all incoming fields.
But that doesn't meet my requirements due to camel case, which I definitely want to keep as the default.
Any ideas on how to do this?
You could create a custom Pipe where you try the different options and finally return the Dto instance:
export class CaseInsensitiveExampleDtoPipe implements PipeTransform{
transform(body: any, metadata: ArgumentMetadata): ExampleDto {
const dto = new ExampleDto();
dto.dateOfBirth = body.dateOfBirth || body.dateofbirth || body.DATEOFBIRTH;
return dto;
}
In your controller you can then use it as follows:
#UsePipes(new CaseInsensitiveExampleDtoPipe())
async postNewExample(#Body() exampleDto: ExampleDto) {
// ...
}
Since JavaScript properties start existing after their initialization, you cannot "see" the definition of dateOfBirth?: string and therefor you won't be able to match it against the received JSON.
A possible solution for that is to enforce the creation of the properties of all of your DTO's with a constructor:
export class ExampleDto {
dateOfBirth: string
constructor(dateOfBirth: string){
this.dateOfBirth = dateOfBirth;
}
}
Then, you'll be able to iterate over the ExampleDto's properties and match them with a pipe (the received type can be derived from metadata):
#Injectable()
export class IgnoreCasePipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
const dto = new metadata.metatype;
const dtoKeys = Object.getOwnPropertyNames(dto);
Object.keys(value).forEach(key => {
const realKey = dtoKeys.find(dtoKey => dtoKey.toLocaleLowerCase() === key.toLocaleLowerCase());
if (realKey) {
dto[realKey] = value[key];
}
});
return dto;
}
}
Either inject it globally in main.ts or wherever it's needed - just bear in mind that you'll need to create a constructor for each DTO.
Note: this would work for a single-level class. If you want to support something like people: PersonDto[] in your classes then you'll need to recursively find all of the nested keys and match them - something like this.

Make class auto inter return types from declaration file

We are using a external package that doesn't have types, recreating it is too much overhaul.
We do know by trial and error the response of i.e (generateWallet) and want to make declarations for them instead of implementing each one.
What we currently have to do
Declaration file
interface ServiceClass {
generateWallet(): Wallet;
}
interface Wallet {
address: string;
privateKey: string;
}
Class
export class Service implements ServiceClass {
constructor() {}
generateWallet(): Wallet {
return externalPackage.generateWallet() // returns any;
}
// We dont want to do this for about hundred different functions
}
Wanted Output
import externalPackage from 'external-package';
const externalPackage.generateWallet(); // Shows return type as (Wallet)
You can add your own type description file for a package that does not have its own types.
Create package_name.d.ts file with a desired types like this:
/* eslint-disable camelcase */
declare module 'external-package' {
export interface Wallet {
address: string;
privateKey: string;
}
interface ExternalPackage {
generateWallet(): Wallet;
}
export default ExternalPackage;
}
Place this file into #types folder and add this folder to tsconfig.json:
{
"compilerOptions": {
... // other options
"typeRoots": [
"#types",
"node_modules/#types"
]
...
}

Redux Toolkit - Slice utility methods

I'm building a React app with redux-toolkit and I'm splitting my store into some slices with redux-toolkit's helper function createSlice.
Here it is a simple use case:
const sidebar = createSlice({
name: "sidebar",
initialState:
{
menus: {}, // Keep track of menus states (guid <-> open/close)
visible: true
},
reducers:
{
show(state, action)
{
state.visible = action.payload.visible;
},
setMenuOpen(state, action)
{
const { id, open } = action.payload;
state.menus[id] = open;
return state;
}
}
});
export default sidebar;
Everything works fine until I "add" actions (that change the store) to the slice but consider your team looking for an utility function "getMenuOpen": this method doesn't change the store (it's not an action and cannot be addeded to reducers object). You can of course read directly the data from the store (state.menus[<your_id>]) but consider a more complex example where manipulating the data requires some library imports, more complex code, etc...I want to modularize/hide each slice as much as possible.
Actually I'm using this workaround:
const sidebar = createSlice({ /* Same previous code... */ });
sidebar.methods =
{
getMenuOpen: (state, id) => state.menus[id]
};
export default sidebar;
The above code allows importing the slice from a component, mapStateToProps to the redux store, and invoke the utilty function getMenuOpen like this:
import sidebar from "./Sidebar.slice";
// Component declaration ...
const mapStateToProps = state => ({
sidebar: state.ui.layout.sidebar,
getMenuOpen(id)
{
return sidebar.methods.getMenuOpen(this.sidebar, id);
}
});
const mapDispatchToProps = dispatch => ({
setMenuOpen: (id, open) => dispatch(sidebar.actions.setMenuOpen({id, open}))
});
The ugly part is that I need to inject the slice node (this.sidebar) as fist param of getMenuOpen because it's not mapped (as for actions with reducers/actions) automatically from redux-toolkit.
So my question is: how can I clean my workaround in order to automatically map the store for utility functions? createSlice doesn't seem to support that but maybe some internal redux's api could help me in mapping my "slice.methods" automatically to the store.
Thanks

Resources