Mocking the Date object accurately in a test using the toHaveBeenCalledWith method in Jest

I'm currently working on unit testing a service that generates a cookie based on an API response I developed.

export interface ISessionService {
    createSession(): Observable<ApplicationSession>;
    validateSession(): Observable<boolean>;
}

The structure of the response is as follows:

export abstract class ApplicationSession {
    public readonly reference: string;
    public readonly dateCreated: Date;
    public readonly expiryDate: Date;
}

When calling SessionService.createSession(), it triggers an rxjs tap and uses another service to create a cookie. My goal is to verify that the cookieService is invoked with the correct parameters. Here's an example:

 describe('given a successful request to create a session', () => {
        beforeEach(() => {
            jestSpyOn(cookiesService, 'setCookie').mockClear();
            jestSpyOn(sessionApi, 'createSession').mockReturnValue(of({
                data: {
                    sessionReference: 'some-reference',
                    dateCreated: '1996-10-15T04:35:32.000Z',
                    expiryDate: '1996-10-15T15:35:32.000Z',
                    statusCode: 200
                },
                exception: null,
                hasError: false
             }));

        });

        it('Then a session cookie is set from the API response', (done) => {
            subject.createSession().subscribe();
            expect(cookiesService.setCookie).toHaveBeenCalledWith(ApplicationCookies.SESSION_COOKIE, {
                dateCreated:'1996-10-15T04:35:32.000Z',
                expiryDate: '1996-10-15T15:35:32.000Z',
                reference: 'some-reference'
            }, { expires: '1996-10-15T15:35:32.000Z', path: "/", sameSite: "strict", secure: true });

            done();
        });
});

Despite my efforts, I keep encountering the same error:

Error: expect(jest.fn()).toHaveBeenCalledWith(...expected)

- Expected
+ Received

  "mock-sessionCookie",
  Object {
-   "dateCreated": "1996-10-15T04:35:32.000Z",
-   "expiryDate": "1996-10-15T15:35:32.000Z",
+   "dateCreated": 1996-10-15T04:35:32.000Z,
+   "expiryDate": 1996-10-15T15:35:32.000Z,
    "reference": "some-reference",
  },
  Object {
-   "expires": "1996-10-15T15:35:32.000Z",
+   "expires": 1996-10-15T15:35:32.000Z,
    "path": "/",
    "sameSite": "strict",
    "secure": true,
  },

Number of calls: 1

I've attempted using date.parse('') but it didn't work... What would be the correct approach to perform this assertion? I'm puzzled by trying to input the date in the test as it's not straightforward like a number.

Appreciate any insights you might have!

Answer №1

The issue you are experiencing is most likely due to the fact that when using mockReturnValue, you are returning a string instead of an actual Date object.

To resolve this, consider updating your mockReturnValue calls to return Date objects instead of strings. For example:

dateCreated: new Date('1996-10-15T04:35:32.000Z'),
expiryDate: new Date('1996-10-15T15:35:32.000Z'),

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript defines types for parameters used in callbacks for an event bus

Encountering a TypeScript error with our custom event bus: TS2345: Argument of type 'unknown' is not assignable to parameter of type 'AccountInfo | undefined'. Type 'unknown The event bus utilizes unknown[] as an argument for ca ...

Obtaining parameter types for functions from deeply nested types

I'm currently facing a challenge involving deeply nested parameters. When dealing with non-nested parameters, everything functions smoothly without any issues export type test = { 'fnc1': () => void, 'fnc2': () => void, ...

imitating an angular http call

My current issue involves a view that accesses an endpoint to transfer a resource to another user. The endpoint URL might resemble: http://mysite/api/{resource}/{Id}/transfer This operation is executed using a PUT request and the payload sent includes: ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

What is the best way to display data stored in local storage using React and Typescript?

Is there a way for the data to be displayed on the browser below the save button when I click save? My setup involves using React with a TypeScript template. function ButtonDefaultExample(props: IButtonExampleProps) { const { disabled, checked } = pro ...

io-ts: Defining mandatory and optional keys within an object using a literal union

I am currently in the process of defining a new codec using io-ts. Once completed, I want the structure to resemble the following: type General = unknown; type SupportedEnv = 'required' | 'optional' type Supported = { required: Gene ...

Leveraging the Typescript Compiler API for transforming a typescript document

I am currently exploring the Typescript Compiler API to develop a tool that merges typescript files. I am curious if there is a way to: Modify the AST after parsing a .ts file. Convert the modified AST back into a .ts file. I have reviewed the documenta ...

ts1109: An error occurred as there was an expectation for an angular

I am encountering an error while creating a simple form with Angular using a reactive form. I'm puzzled as to why it's indicating that something is missing: Although I have created forms numerous times before, this is the first instance of such ...

Organizing information based on date attribute in R

I'm facing issues using the date variable in my dataset to create 6-month time period categories. I need to categorize the years between 2017-1-1 and 2020-6-30 into different time periods, such as from 2017-1-1 to 2017-6-30, and so on until 2020-6-30. ...

How to show the current week using React Native

Looking to show the current week of the month in a specific format using react-native: (Week 2: 05.10 - 11.10) (for example, displaying week 2 of the current month) Any ideas on how to make this happen? I'm aware of packages like momentjs that can ...

Error in Typescript: Uncaught ReferenceError - "exports" is undefined

Encountering an error message (Uncaught ReferenceError: exports is not defined) when attempting to import other TypeScript files in the main app.ts app.ts import { LanguagesConfigs } from './LanguagesConfigs'; let languagesConfigs = new Languag ...

Angular 8 delivers an observable as a result following a series of asynchronous requests

I am working on a simple function that executes 3 asynchronous functions in sequence: fetchData() { this.fetchUsers('2') .pipe( flatMap((data: any) => { return this.fetchPosts(data.id); }), fl ...

Expanding the functionality of an external module using d.ts in a TypeScript project

Currently, I am in the process of developing a nodejs application using typescript with multiple external libraries such as express.js. Like many other libraries, express is also designed to be extendable. I am looking to enhance it by including a custom ...

What is the best way to effectively use combinedLatestWith?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/country-card/country-card.component.html I am currently working on implementing a search bar in Angular that filters the "countries$" Observable based on user input. My approach involves creatin ...

Modifying preset values in settings.json within the [Extension Development Host] environment

Currently, I am developing an extension in VS Code and I want to implement a feature where a pop-up with a text message input appears when the extension first runs. The user input from the pop-up will be used to modify the default settings in the settings. ...

Exploring the Implementation of Data Transfer Objects (DTO) in the Services File of a Nest

I am trying to retrieve data of a specific person from mongodb based on their username and password values, but instead of getting the data of that particular person, I am getting all the data from the database. Below is the code for the DTO: import {IsS ...

I'm experiencing some difficulties utilizing the return value from a function in Typescript

I am looking for a way to iterate through an array to check if a node has child nodes and whether it is compatible with the user's role. My initial idea was to use "for (let entry of someArray)" to access each node value in the array. However, the "s ...

I'm encountering an issue with one of my routes not loading correctly in Angular 4 Universal

I have been working on implementing Universal and I believe I've made significant progress. My project is built on this seed. However, when I run "npm start", only the /about and /contact pages render successfully. The /home page does not render at al ...

ngx hierarchical dropdown

Is it possible that the 'disabled' attribute is not a recognized property of the 'ngx-dropdown-treeview' component? The ngxDisabledOnSelector property seems to be malfunctioning in my specific case. This is my code snippet: <ngx-dr ...

Join and Navigate in Angular 2

Attempting to retrieve information from a JSON file has been an issue for me. Here is the code snippet: ngOnInit() { this.http.get('assets/json/buildings.json', { responseType: 'text'}) .map(response => response) .subsc ...