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

时间:2018-12-10 10:29:37

标签: node.js unit-testing jestjs

我有以下要测试的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));

什么? 我对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 |

0 个答案:

没有答案