编辑:解决方案是删除let transport =
,然后创建Mailgun的新实例,然后构造新的MailgunTransport对象。
describe('Test MailgunTransport returns MailgunResponse', async () => {
let mailgunResponse = new MailgunResponse(message, {});
sinon.stub(MailgunTransport.prototype, 'sendMessage').resolves(mailgunResponse);
let apiKey = '';
let domain = '';
let mailgunTransport = new Mailgun({ apiKey, domain });
let transport = new MailgunTransport(mailgunTransport);
...
});
具有权威的人请标记为已解决。谢谢。
我正在用sinon设置单元测试,但无法使存根函数正常工作。
尝试存根和模拟都没有成功。 mailer.send(message)方法返回transport.sendMessage(message)。根据错误消息“ TypeError:this.transport.sendMessage不是函数”,看来存根无法正常工作。
测试用例
// Test Case
describe('Test MailgunTransport returns MailgunResponse', () => {
let mailgunResponse = new MailgunResponse(message, {});
let transport = sinon.stub(MailgunTransport.prototype, 'sendMessage')
.resolves(mailgunResponse);
// let transport2 = sinon.mock(MailgunTransport).expects('sendMessage').once().resolves(mailgunResponse);
let mailer = new Mailer(
<any> transport,
new Email('system@test.com', 'System'),
);
let response = mailer.send(message);
describe('assertInstanceOf', () => {
it('MailgunResponse.class', () => {
expect(response).to.be.an.instanceof(MailgunResponse);
});
});
});
Mailer.ts
import Email from './Email';
import Message from './Message';
import MockResponse from './Transport/MockResponse';
import ResponseInterface from './Transport/ResponseInterface';
import TransportInterface from './Transport/TransportInterface';
export default class Mailer {
private transport: TransportInterface;
private delivery: boolean;
constructor(
transport: TransportInterface,
delivery: boolean = true
) {
this.transport = transport;
this.delivery = delivery;
}
public send(message: Message): Promise<ResponseInterface> | ResponseInterface {
if (this.delivery) {
return this.transport.sendMessage(message);
}
return new MockResponse(message);
}
}
MailgunTransport.ts
...
export default class MailgunTransport implements TransportInterface {
private mailgun: Mailgun;
constructor(mailgun: Mailgun) {
this.mailgun = mailgun;
}
public async sendMessage(message: Message): Promise<MailgunResponse> {
let data = {}
return new MailgunResponse(message, await this.mailgun.messages().send(data, (error, body) => {
console.error(error);
console.log(body);
}));
}
}
预期结果是'sendMessage'方法的存根版本,但我一直在出错。我不确定我缺少什么。