【发布时间】:2021-04-30 04:40:57
【问题描述】:
我得到了一个简单的单元测试,代码如下:
my-pubsub.spec.ts
import * as tsSinon from 'ts-sinon';
import { myPubSubFunction } from './my-pubsub';
import * as sendEmail from './send-mail';
describe("Notifications PubSub tests", () => {
it("Should trigger audit", (done) => {
const today = new Date()
const data = {
( my data )
}
const spy = tsSinon.default.spy(sendEmail, "sendNotificationMessage")
const dataBuffer = Buffer.from(JSON.stringify(data))
// Call tested function and verify its behavior
myPubSubFunction(dataBuffer)
setTimeout(() => {
// check if spy was called
tsSinon.default.assert.calledOnce(spy)
done()
}, 100)
})
})
而my-pubsub.ts 收到了来自send-mail 的函数调用,其中包含设置 Api 密钥的函数
import * as sgMail from '@sendgrid/mail';
sgMail.setApiKey(
"MyKey"
) // error in here
export function sendNotificationMessage(mailConfig: any) {
const defaultConfig = {
from: {
email: "noreply@mymail.com",
name: "my name",
},
template_id: "my template",
}
const msg = { ...defaultConfig, ...mailConfig }
return sgMail.send(msg)
}
但是在运行我的测试时出现以下错误TypeError: sgMail.setApiKey is not a function
编辑:向发送邮件代码添加了更多代码。
下面你可以找到更多关于my-pubsub.ts的代码
my-pubsub.ts
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
import moment = require('moment');
import { IModel, ModelType } from '../models/model.model';
import { sendNotificationMessage } from '../shared/send-mail';
const { PubSub } = require("@google-cloud/pubsub")
try {
admin.initializeApp()
} catch (e) {}
const db = admin.firestore()
const pubSubClient = new PubSub()
export const myPubSubTrigger = functions.pubsub
.topic("on-trigger")
.onPublish(async (message) => {
console.log("version 1")
const myMessage = Buffer.from(message.data, "base64").toString("utf-8")
const data: IModel = JSON.parse(myMessage)
( logic to create my object )
/**
* Send email
*/
const result: any = await sendNotificationMessage(myObject)
/**
* Check result
*/
if (result[0].statusCode === 202) {
await docRef.update({ emailSent: true })
}
( another publish to audit the action )
})
【问题讨论】:
-
提供
myPubSubFunction和sendEmail的代码 -
@slideshowp2 我在 sendEmail 中添加了更多代码,并添加了
myPubSubFunction的代码。我认为也许我需要存根 sendEmail 文件或将其声明为模块。不太确定,因为我以前只使用过 Jasmine 和 Karma,而且是很久以前的事了。
标签: node.js typescript unit-testing mocha.js sinon