Unit testing 如何在It块内部使用模拟代码
我试着在根级别上开玩笑,它工作得很好。但内部It块中使用的jest mock无法解决此问题 型号Unit testing 如何在It块内部使用模拟代码,unit-testing,mocking,jestjs,ts-jest,Unit Testing,Mocking,Jestjs,Ts Jest,我试着在根级别上开玩笑,它工作得很好。但内部It块中使用的jest mock无法解决此问题 型号 email = (to: string, key: string) => { const emailParam = { from: 'yzx@gmail.com', to: to, subject: 'Hai', html: `<p>hello.</p&g
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);
});
});
错误案例
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函数。您不应该在
It
内模拟依赖项。通常的方法是在每次之前的方法中提供模拟,并最终在每次
之后使用重置模拟
您可以在此处找到其他信息: