简体   繁体   中英

How to mock Date object in typescript using Jest?

I am trying to mock a date object that will be utilized for all the unit test cases. I have many references for javascript, but that is not working in typescript due to type errors. can anyone provide a solution to overcome this issue?

// sampleMethod() Test Suite
describe('sample Method', () => {
    it('should match two objects', () => {
        // Preparing
        const sampleRequest: sampleRequestType = {
            key: '0',
            status: 'success',
            creation_time: new Date(),
            attempts: 0,
            last_attempt_time: new Date()
        };
        // Executing
        const result = sampleobject.sampleMethod();
        // Verifying
        expect(result).toEqual(sampleRequest); // assume result also return the same value as sampleRequest
    });
});

As Jest is developed on top of jasmine, you can use this

const mockDate = new Date(1434319925275);
spyOn(window, 'Date').and.callFake(() => {
return mockDate;
});

@hari you can refactor your sampleMethod and remove the hard dependency on the Date object.

Instead of instantiating directly the Date object (new Date) inside of the method , change the method and receive the date object as parameter.

In that way , you can easily mock the Date dependency.

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