简体   繁体   中英

Mock a class for testing with Typescript and Jest

I am trying to write testing using Jest with Angular and Typescript, but I cannot quite understand how to mock the functions within a class. I have created a very simple example to try to get some help in understanding what I do not follow.

test-service.ts (simple class)

export class TestService{
    constructor() { }

    GetRandom(): number {
        return Math.floor(Math.random() * 100);
    }
}

This is simple class just to show something I am trying to mock. As the function is returning a random number, you cannot test it. This is the sample I am trying to simply illustrate external processes that could have returned anything, and want to check the data returned that my code would be working.

test-service.spec.ts

import { TestBed, ComponentFixture } from '@angular/core/testing';

import { NO_ERRORS_SCHEMA } from '@angular/core';

jest.mock('./test-service');
import { TestService } from './test-service';

describe('TestService', () => {
    let TestObject: TestService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ ],
            providers: [ ]
        });
    });

    describe('Sample Test', () => {
        test('Random Number should be mocked by Jest', () => {
            ...  // What do to here??
            expect(TestObject.GetRandom()).toBe(5);  // How do I get the mock here?

        });
    });
});

I do not know how to make the random number return a simple number (for instance 5) for the test.

First, you have to create a method to replace the implementation of your desired mocked methods. For example, I created it in the class TestUtil :

export class TestUtil {

 public static mockService(service: any, methods: string[]) {
   @Injectable()
   class MockedClass {
   }

   methods.forEach(method => MockedClass.prototype[method] = Observable.of({}));

   return {provide: service, useClass: MockedClass};
  }
}

And then you can use it to provide a mocked class of TestService in your test module.

describe('TestService', () => {
  let TestObject: TestService;

  beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [TestUtil.mockService(TestService, ['GetRandom'])]
    });
  });

  beforeEach(inject([TestService], (injectedTestService: TestService) => {
    TestObject = injectedTestService;
  }));

  describe('Sample Test', () => {
    test('Random Number is mocked by You', () => {
       spyOn(TestObject, "GetRandom").and.returnValue(5);
       expect(TestObject.GetRandom()).toBe(5);
    });
  });
});

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