-->

Welcome to our Coding with python Page!!! hier you find various code with PHP, Python, AI, Cyber, etc ... Electricity, Energy, Nuclear Power

Saturday, 31 October 2020

How to strongly type jest mocks

#typescript, #jestjs, #typescript-typings, #ts-jest, 


To strongly type my jest mocks. To a certain extent, I can make it work.

When I use mocks (the way I currently do) the return type is of the original type but when I have to access any method added by Jest I have to typecast it so jest.Mock to access a method. 

 I've tried to work with jest.Mockjest.Mockedjest.MockInstance.


class MyTest {
    constructor(private readonly msg: string) {}

    public foo(): string {
        return this.msg;
    }
}

const myTestMock: jest.Mock<MyTest, [string]> = jest.fn<MyTest, [string]>(() => ({
    msg: 'private',
    foo: jest.fn().mockReturnValue('aaa'),
}));
// Results in error:
// Type '{ msg: string; foo: Mock<any, any>; }' is not assignable to type 'MyTest'.
// Property 'msg' is private in type 'MyTest' but not in type '{ msg: string; foo: Mock<any, any>; }'

const myTestMockInstance: MyTest = new myTestMock('a');
console.log(myTestMockInstance.foo()); // --> aaa

// Accessing jest mock methods:
(<jest.Mock>myTestMockInstance).mockClear(); // <-- can this be done without type casting

Dirty workaround:

const myTestMock: jest.Mock<MyTest, [string]> = jest.fn<MyTest, [string]>(
    // Cast to any to satisfy TS
    (): any => ({
        msg: 'private',
        foo: jest.fn().mockReturnValue('aaa'),
    })
);
xxxxxxxxxx

  1. There is a helper which makes types: look ts-jest

  2. usually you should test public interface, not an implementation. Instead of testing private methods you could extract that logic to a public interface (maybe to another class that provides the interface)

how to create a database from batchfile

this script allow you to Create database and tables from batch file

for this save this content in a text editor 
and save it as .bat file



@echo off

:: This batch allow you to create a database

Title Projet xxxx.

 

Echo Database creation 

Echo starting script ... Please wait...

set /p dbname= "enter the name of the new db:"

createdb -h localhost -p 5432 -U postgres -E UTF-8 -e %dbname%

Echo Database created  ...

 

echo end of the process

xxx

create a postgresql database using a batch file


how to restore postgresql database from a backup file

 in order to restore a postgresql database based on a backup file, use a command line (cmd) and enter the following code:




pg_restore -h localhost -p 5432 -U postgres -d testdatabse -v d:\db.backup


with 

localhost: your host name

5432: the used port for postgresql

testdatabase: the new database in which you want to retore you backup file

d:\db.backup: the database backup file.

don't hesitate to write your feedback or comment


Rank

seo