DEV Community

Cover image for Test for dynamically created elements like time and token with jest(spys)
Clara Situma
Clara Situma

Posted on

Test for dynamically created elements like time and token with jest(spys)

Jest is a popular JavaScript testing framework that provides a variety of powerful features for testing your code. One such feature is the spyOn method, which allows you to create a spy on a specific method of an object.

In this article, we'll take a look at how to use the spyOn method, using the following code example as a guide:


//code to be tested 
private generateExpirationTime() {
    return new Date(Date.now() + 60 * 60 * 1000);
}

private generateRandomTokenId() {
    return Math.random().toString(36).slice(2);
}

//the test 

test.only('should return sessionToken for valid credentials', async() => { 
    jest.spyOn(global.Math, 'random').mockReturnValueOnce(0);
    jest.spyOn(global.Date, 'now').mockReturnValueOnce(0);

    UserCredentialsDbAccessMock.getUserCredential.mockResolvedValueOnce({
        username:'someUser',
        accessRights:[1,2,3]
    })

    const expectedSessionToken:SessionToken ={ 
        userName:'someUser',
        accessRights:[1,2,3],
        valid:true,
        tokenId:"",
        expirationTime: new Date(60 * 60 * 1000)
    }

    const sessionToken = await authorizer.generateToken(someAccount)
    expect(expectedSessionToken).toEqual(sessionToken);
    expect(SessionTokenDBAccessMock.storeSessionToken).toBeCalledWith(sessionToken);
})

Enter fullscreen mode Exit fullscreen mode

In this example, we are testing a function generateToken that internally uses generateExpirationTime and generateRandomTokenId functions.

  • The jest.spyOn(global.Math, 'random') is used to create a spy on the Math.random() method

  • The jest.spyOn(global.Date, 'now')is used to create a spy on the Date.now() method.

  • The mockReturnValueOncemethod is then used to specify a value that the spy should return when it is called. In this case, jest.spyOn(global.Math, 'random').mockReturnValueOnce(0) means that the Math.random() spy will return 0 when it is called for the first time.

  • Similarly, jest.spyOn(global.Date, 'now').mockReturnValueOnce(0)means that the Date.now() spy will return 0 when it is called for the first time.

summary

Spies are useful for testing because they allow you to control the behavior of specific methods in order to test different scenarios.

  • In this case, by using spyOn to replace the Math.random() and Date.now() methods with spied versions that return specific values, the generateExpirationTime() and generateRandomTokenId() methods can be tested with known input.

Additionally, UserCredentialsDbAccessMock.getUserCredential.mockResolvedValueOnce({username:'someUser',accessRights:[1,2,3]}) is used to mock the return value of the function getUserCredential of `User

Top comments (0)