单元测试:如何使用JEST测试对第三方库的请求?

loading...


0

我有以下Node.js javascript文件我想测试:(目的是发送带有安全OAuth的电子邮件)

index.js

const nodemailer = require("nodemailer");
    const { OAuth2Client } = require('google-auth-library');

    // Download OAuth2 config from the Google console
    const keys = require("./keys.json");

    const oAuth2Client = new OAuth2Client(
      keys.web.client_id,
      keys.web.client_secret,
      keys.web.redirect_uris[0]
    );

    // First refresh_token from playground in console
    oAuth2Client.setCredentials({
      refresh_token: "1/xxxxxxxxxxxxxxxxxxxxxxxxxxx"
    });

    async function getAccessToken() {
      return await oAuth2Client.getAccessToken();
    }

    getAccessToken()
    .then(response => {
      const accessToken = response.res.data.access_token;
      const refreshToken = response.res.data.refresh_token;
      const smtpTransport = nodemailer.createTransport({
        service: "gmail",
        auth: {
          type: "OAuth2",
          user: "john.doe@lexample.com",
          clientSecret: keys.web.client_secret,
          refreshToken: refreshToken,
          accessToken: accessToken
        }
      })
      const mailOptions = {
        from: "john.doe@lexample.com",
        to: "john.doe@lexample.com",
        subject: "Node.js Email With Secure OAuth",
        generateTextFromHTML: true,
        html: "<b>test</b>"
      }
      smtpTransport.sendMail(mailOptions, (error, response) => {
        error ? console.log("ERROR: ", error) : console.log("RESPONSE: ", response);
        smtpTransport.close();
      })
    })
    .catch(err => console.log("ACCESS TOKEN ERROR: ", err));

什么 ?我是一个小st(更确实......)迷失了JEST嘲笑......我应该测试这段代码的哪些部分以及我应该模拟哪些模块/函数?

怎么样?我试着写第一个测试,但它失败了:

index.spec.js

import { OAuth2Client } from "google-auth-library";

    jest.genMockFromModule('google-auth-library');
    jest.mock('google-auth-library');

    const mockAuthClient = {
      setCredentials: jest.fn()
    }
    OAuth2Client.mockImplementation(() => mockAuthClient);

    describe('OAuth2Client', () => {
      it('should call the setCredentials method of the mockAuthClient', () => {
        OAuth2Client.setCredentials({ refresh_token: "xxxxx" });
        expect(mockAuthClient.setCredentials).toHaveBeenCalledWith('refresh_token');
      })

    });

console.log

TypeError: _googleAuthLibrary.OAuth2Client.setCredentials is not a function

          11 | describe('OAuth2Client', () => {
          12 |   it('should call the setCredentials method of the mockAuthClient', () => {
        > 13 |     OAuth2Client.setCredentials({ refresh_token: "xxxxx" });
             |                  ^
          14 |     expect(mockAuthClient.setCredentials).toHaveBeenCalledWith('refresh_token');
          15 |   })
          16 |

loading...

0回答

No Data

评论

暂时没有评论!