【问题标题】:How to stub nested dependecies with ts-sinon如何使用 ts-sinon 存根嵌套依赖项
【发布时间】: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 )
  })

【问题讨论】:

  • 提供myPubSubFunctionsendEmail的代码
  • @slideshowp2 我在 sendEmail 中添加了更多代码,并添加了 myPubSubFunction 的代码。我认为也许我需要存根 sendEmail 文件或将其声明为模块。不太确定,因为我以前只使用过 Jasmine 和 Karma,而且是很久以前的事了。

标签: node.js typescript unit-testing mocha.js sinon


【解决方案1】:

问题不在于测试本身,而是@sendgrid/mail 的类型定义不正确:

// OK
import sgMail from "@sendgrid/mail";
import { default as sgMail2 } from "@sendgrid/mail";

console.log(sgMail === sgMail2);

sgMail.setApiKey("SG.key");
sgMail2.setApiKey("SG.key2");

// BROKEN
// type definition does not match runtime shape
import * as sgMailIncorrectlyTyped from "@sendgrid/mail";
console.log(sgMailIncorrectlyTyped, sgMailIncorrectlyTyped.setApiKey === undefined);

STACKBLITZ

【讨论】:

  • 谢谢,将导入更改为import sgMail from "@sendgrid/mail"; 解决了问题。当可用选择时,我会分配赏金(从现在开始21小时) span>
猜你喜欢
  • 1970-01-01
  • 2015-02-12
  • 2020-01-03
  • 1970-01-01
  • 2021-06-18
  • 2015-01-11
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多