【问题标题】:How to jest mock code using in inside It block如何在 It 块内使用嘲笑模拟代码
【发布时间】:2020-05-16 18:36:17
【问题描述】:

我试图在根级别开玩笑,它工作正常。但是在 It 块内部使用的玩笑模拟不起作用如何解决这个问题。

型号


    email = (to: string, key: string) => {
        const emailParam = {
            from: 'yzx@gmail.com',
            to: to,
            subject: 'Hai',
            html: `<p>hello.</p>`
        };
        return Mailgun.sendEmail(emailParam);
    };

成功案例

                jest.mock('mailgun-js', () => {
                    const mockMailgun = {
                        messages: jest.fn().mockReturnThis(),
                        send: jest.fn(() => ({
                            id: '1',
                            message: 'Email send successfully.',
                        })),
                    };
                    return jest.fn(() => mockMailgun);
                });    

    describe('Email', () => {
        it('', async () => {
            const to = 'xyz@gmail.com'  
            const key = 1234
            // Executing
            const result = model.email(to, key);
            // Verifying
            expect(result.message).toBe('Email send successfully.');
            expect(mailgun.messages().send).toHaveBeenCalledWith(emailParams);
        });
    });

错误案例

    describe('Email', () => {
        it('', async () => {

          jest.mock('mailgun-js', () => {
               const mockMailgun = {
               messages: jest.fn().mockReturnThis(),
               send: jest.fn(() => ({
                        id: '1',
                        message: 'Email send successfully.',
               })),
             };
             return jest.fn(() => mockMailgun);
          }); 

            const to = 'xyz@gmail.com'  
            const key = 1234
            // Executing
            const result = model.email(to, key);
            // Verifying
            expect(result.message).toBe('Email send successfully.');
            expect(mailgun.messages().send).toHaveBeenCalledWith(emailParams);
        });
    });

我试图在 It 块内开玩笑。它不起作用抛出错误。如何在 It 块中使用 jest mock 函数。

【问题讨论】:

    标签: unit-testing mocking jestjs ts-jest


    【解决方案1】:

    您不应该在 it 中模拟依赖项。通常的方法是在beforeEach 方法期间提供模拟,并最终使用afterEach 重置它们。

    您可以在此处找到更多信息:https://github.com/facebook/jest/issues/2582

    【讨论】:

      猜你喜欢
      • 2015-12-18
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 2011-04-10
      相关资源
      最近更新 更多