【发布时间】: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