【问题标题】:jest - mocking Date correctly when calling toHaveBeenCalledWith开玩笑 - 调用 toHaveBeenCalledWith 时正确模拟日期
【发布时间】:2021-12-30 19:39:18
【问题描述】:

我正在尝试对一项服务进行单元测试,该服务根据我创建的 API 的响应创建 cookie。

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

响应看起来像这样:

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

SessionService.createSession() 被调用时,它会执行一个rxjs 点击并通过另一个服务创建一个cookie,我正在尝试测试是否使用正确的参数调用了cookieService。像这样:

 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();
        });
});

不过,我似乎总是遇到同样的错误:

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

我尝试过使用date.parse(''),但这不起作用......做出这个断言的正确方法是什么?我想不通。我不能像测试显示的那样只输入日期,因为它不是数字。

谢谢

【问题讨论】:

    标签: typescript unit-testing date jestjs


    【解决方案1】:

    这个问题很可能发生,因为您对mockReturnValue 的调用返回的是日期字符串而不是日期对象。

    因此尝试更改您的 mockReturnValue 调用以返回 Date 对象而不是字符串,例如

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

    【讨论】:

    • 是的,我完全忘记了我将从 API 返回的日期传递给 Date 对象。谢谢你!
    • 没问题@MarcFreeman。太好了,它解决了您的问题:)
    猜你喜欢
    • 2019-11-08
    • 2018-05-05
    • 2019-10-18
    • 2019-11-19
    • 2019-10-27
    • 2020-03-15
    • 1970-01-01
    • 2018-12-27
    • 2017-07-01
    相关资源
    最近更新 更多