Tags down


How to allow partial TypeScript types when mocking functions - Jest, TypeScript

By : yash
Date : October 16 2020, 06:10 PM
This might help you I have a function which I would like to mock for testing purposes in TypeScript. In my tests, all I care about are the json and the status. However, when using Jest's jest.spyOn the type of my mocked function is set to return a http Response type. This is awkward as it means I have to manually go and implement a bunch of functions and properties that are irrelevant and arbitrary. , You can use as...
code :
export function mockApi(json: object, status: number): void {
  ).mockImplementation(() =>
      json: () => Promise.resolve(json),
    } as http.Response), // <-- here
type X {
  a: number
  b: number

const x = { a: 2 } as X // OK
const y = { a: 3, c: 2 } as X // NOT OK, because c does not exist in X

Share : facebook icon twitter icon

Mocking express and mongoose with jest in typescript

By : Gabriel Zanghelini
Date : March 29 2020, 07:55 AM
wish of those help To mock the Request and Response objects, you simply just pass them in with the values that you are using. In your case, this looks like this:
code :
import { Request, Response, NextFunction } from 'express';
import { Foo } from '../../src/models/Foo';
import * as fooController from '../../src/controllers/foo';
import { doesNotReject } from 'assert';

describe('createFoo', async () => {
  it('should add bars to the foo', async () => {
     * Spy on the model save function and return a completed promise.
     * We are not testing the model here, only the controller so this is ok.
    jest.spyOn(Foo.prototype, 'save').mockImplementationOnce(() => Promise.resolve());

     * Create a mock request and set type to any to tell typescript to ignore type checking
    const mockRequest: any = {
      user: {
        _id: 1234,
      body: {
        bars: ['baz', 'qux', 'quux'],

     * Create a mock repsonse with only the methods that are called in the controller and
     * record their output with jest.fn()
    const mockResponse: any = {
      status: jest.fn(),
      json: jest.fn(),

     * Create a mock next function. It is okay to set its type to Express's NextFunction because
     * we are mocking the entire function.
    const mockNext: NextFunction = jest.fn();

    await fooController.createFoo(mockRequest, mockResponse, mockNext);



Typescript,testing Api calls in Redux actions, mocking class in Enzyme, Jest

By : user2635658
Date : March 29 2020, 07:55 AM
it should still fix some issue You know you're screwed when you post a question to stackoverflow and get 0 answers and 0 responses in over a week... Not ideal but I've found a workaround to override the Api class in my thunk actions, instead of importing the Api class into all my action files and calling it directly, I now only import it into the root of my project (App.tsx) and make it global as below (stripped down to it's bare minimum).
code :
import * as React from 'react';
import Api from './api/Api';

export interface State {


export interface Props {


export class App extends React.Component<Props, State> {

    state = {


    componentWillMount = () => {
        (global as any).Api = Api;

    public render() {
        return (


export default App;
export const getAlldata = (id: string) => {
    return (dispatch: any) => {
        dispatch(beginAjaxRequest(id, types.BEGIN_GET_DATA_AJAX));
        return (global as any).Api.get("/data/data").then((response: any) => {
            dispatch(getDataSuccess(response.data, id))
        }).catch((error) => {
            dispatch(handleAjaxError(id, new Alert({ id: id, title: "Error getting data", message: error.toString(), timestamp: Date.now(), error: true })));
import * as Enzyme from 'enzyme';
import Api from './__mocks__/Api';
const Adapter = require("enzyme-adapter-react-16");

(global as any).Api = Api;

Enzyme.configure({ adapter: new Adapter() });

When mocking a class in typescript using jest/ts-jest I am getting "TypeError: "X".default is not a const

By : Leandro
Date : March 29 2020, 07:55 AM
This might help you Because you are using ES2015 imports for your code it expects the default export of your module to be available, but in the mock you do not provide one. Fix is very simple:
code :
jest.mock('../../utils/storage', () => {
    return { // need to add this nested `default` property
        default: jest.fn().mockImplementation(() => {
            return {
                getAdaptiveCard: mockGetAdaptiveCard

Mocking Express Request with Jest and Typescript using correct types

By : user3196646
Date : March 29 2020, 07:55 AM
it helps some times Your mock data type doesn't have to perfectly fit the actual data. Well, it doesn't by definition. It's just a mock, right?
What you need is a type assertion. It's a way to tell TypeScript "Okay bro, I know what I'm doing here.".
code :
const mockRequest = {
    body: {
    firstName: 'J',
    lastName: 'Doe',
    email: 'jdoe@abc123.com',
    password: 'Abcd1234',
    passwordConfirm: 'Abcd1234',
    company: 'ABC Inc.',
} as Request;
const x: number = "not a number :wink:" as any as number;

Mocking/Stubbing a Typescript interface with jest

By : A Colder
Date : March 29 2020, 07:55 AM
Hope this helps I ended up using type assertion for it which is a bit of a hack. So something like:
code :
const res = {} as Express.Response;
Related Posts Related Posts :
  • Typescript type safe HTTP post not really type safe
  • Need to click twice in KeyboardAvoidingView even when keyboardshouldpersisttaps is always
  • Typescript interface with keys of Generic
  • Nuxt custom plugin exports is not defined
  • TypeGraphQL use TypeORM's findAndCount method
  • Defining a list of tuples with optional first and last elements
  • Error Message: "An interface can only extend an object type or intersection of object types with statically known m
  • Typescript: Create object with same keys but different values
  • ServiceStack - Cannot get headers from in Typescript client ResponseFilter
  • Object.entries(qs).forEach(...) - resolve lambda ignoring type annotations
  • Accessing generics from inherited type
  • Deriving TypeScript interface from object literal
  • How to declare default-function for a class?
  • Use an object as a map's key in the value
  • How can I ignore operating system font in react-native?
  • rxjs: Map adding field
  • How to use Mocha and Jest with TypeScript without conflicts?
  • Vue 2 + TypeScript: Avoid mutating Prop directly - in a class based component with vue-property-decorator
  • Is function () { this.array = [newElem, ...array] } pure?
  • Understanding .tsconfig file
  • Compare two interfaces at runtime
  • Cant get variable in data
  • TypeScript inferencing with process.exit
  • Using the keys of an object literal as a Typescript type?
  • Retrieve current value of an observable
  • TypeScript: Declaring a callable type as a class method type
  • TestCafe - Checking if the hyperlink is working - redirection to an external email provider
  • Typescript, from us currency to es currency
  • How to properly define global enum in Typescript
  • Protractor typescript Error: WebDriverError: java.net.ConnectException: Connection refused: connect while selecting valu
  • How can I write extension for generic class in typescript as getter
  • TSLint: ordered-imports configuration
  • Module.exports with es6 import for webpack.config.ts in typescript
  • How can I find where TS type is defined in my app?
  • Using externally defined component with Vue and TypeScript class decorator syntax
  • typescript multiple generic cannot infered properly
  • Typescript switch case confusing compiler
  • Type guard with complement in false branch
  • Manually widen type
  • How do I type for arrays with ordered types of unknown length?
  • could be instantiated with a different subtype of constraint 'object'
  • Fix "Continue without scanning the task output" in Visual Studio Code
  • Typing declaration disambiguate Object or Function
  • TypeScript dynamically derived fields from another type
  • How can I create a generic type for a dynamic generated object created from an array
  • Why is typescript upset about comparing to undefined?
  • Nested queries in Apollo Server
  • How to run TypeScript from local directory instead of global
  • Typescript gives different errors in vscode than through webpack
  • Switching based on object type
  • winston custom transport with typescript
  • Enforce explicit function return type annotations?
  • How to match nested Keys in Typescript
  • Typescript allow extension of AxiosConfig
  • Can one represent indexable signatures in io-ts
  • Why won't TS let me index into a compatible object type?
  • Cannot find module that is defined in tsconfig `paths`
  • TypeScript function generic can only work for function overload with more than one signatures
  • Is it possible to have a function accept class instances, but not accept plain objects?
  • Extending a union type exactly
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk