简体   繁体   中英

Jest and Typescript - Mocking a const in a function

New to Jest here and not sure how I would do this:

Say I have some function that contains a const that I've set to a specific type ( newArtist ):

export class myTestClass {
    async map(document: string) {
        const artist: newArtist = document.metadata.artist;
        ...
        }
}

And along with that I have:

export interface newArtist {
    name: string;
    title: string;
}

Now when I write a test, if I do say something like:

it("My example test", async () => {
    const result: any = await new myTestClass(__context()).map({
        name: "An Artist"
        title: null
    });
        ...
}

The test will fail because title is set to null. I need that interface to be a little different for the purposes of the test - basically to be be something like:

export interface newArtist {
    name: string;
    title: string | null;
}

How can I do that? I've seen mocking classes, but wouldn't that mean I end up copying/pasting all the map function code?

Any help appreciated.

Thanks.

I am not very clear what do you try to do. The code you provide is incorrect.

For me, the below code works fine with typescript and jest. Please give more information.

index.ts :

export interface INewArtist {
  name: string;
  title: string | null;
}

export interface IDocument {
  metadata: {
    artist: INewArtist;
  };
}

export class MyTestClass {
  constructor(private readonly ctx) {}
  public async map(document: IDocument) {
    const artist: INewArtist = document.metadata.artist;
  }
}

Unit test:

import { MyTestClass, IDocument } from './';

// tslint:disable-next-line: variable-name
const __context = () => {};

describe('MyTestClass', () => {
  it('My example test', async () => {
    const document: IDocument = {
      metadata: {
        artist: {
          name: 'An Artist',
          title: null
        }
      }
    };

    const result: any = await new MyTestClass(__context()).map(document);
  });
});

Unit test result:

 PASS  src/stackoverflow/56847385/index.spec.ts
  MyTestClass
    ✓ My example test (3ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.396s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM