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!