如何在It块内部使用嘲笑模拟代码

时间:2020-01-31 04:46:18

标签: unit-testing mocking jestjs ts-jest

我试图在根级别开玩笑,它工作正常。但是在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模拟功能。

1 个答案:

答案 0 :(得分:0)

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

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