使用 mocha 验证电子邮件内容

Verify email content using mocha

我正在使用 Node JS、mocha 和 googleapi 编写测试来验证电子邮件内容

当我 运行 将 googleapi 作为独立的节点 js 文件时,我能够收到邮件,但是当我将它与 mocha 测试集成时,我没有看到任何结果,请帮助

测试规范文件 (verify.js)

var checkEmail = require('../shared/checkEmail');
const { google } = require('googleapis');
var expect = require('chai').expect;
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
const { isNullOrUndefined } = require('util');

chai.use(chaiAsPromised);
chai.should();

var emailRecords = new Array();
var content;
var auth;

describe('GMAIL Testing', function () {
    before('Connect to Gmail server', function () {

        content = checkEmail.getAuthentication();
        auth = checkEmail.authorize(content);

        // Random test data
        var a = [{ "Id": "123", "MsgId": "34677", "Type": "aaa", "Subject": "subxxxx", "ToAddress": "abc@gmail.com", "ToName": "ABC", "DateCreated": "2020-07-09T18:25:38.047Z" }];
        emailRecords.push(a);
        var b = [{ "Id": "456", "MsgId": "34655", "Type": "bbb", "Subject": "subject", "ToAddress": "abc@gmail.com", "ToName": "ABC", "DateCreated": "2020-06-09T18:25:38.047Z" }];
        emailRecords.push(b);
    });


    it('Gmail Verification', function () {
        emailRecords.forEach(element => {
            const gmail = google.gmail({ version: 'v1', auth });
            var query = "from:noreply@somedomain.com " + element[0].MsgId;
            console.log('getting mail '+ element[0].MsgId);
            gmail.users.messages.list({
                userId: 'me',
                q: query
            }, (err, res) => {
                if (err) return console.log('The API returned an error: ' + err);

                var mails = res.data.messages;
                console.log('mail(s) found');
                expect(mails.length).to.be.at.least(1);
            });
            console.log('completed search');
        });
    });
});

实用程序文件 checkEmail.js 参考 -> Gmail API

const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');
var base64 = require('js-base64').Base64;
const cheerio = require('cheerio');
var open = require('open');
const { isNullOrUndefined } = require('util');
var Mailparser = require('mailparser').MailParser;

const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

module.exports = new class checkEmail {


    getAuthentication() {
        // Load client secrets from a local file.
        console.log('getting auth');
        this.content = JSON.parse(fs.readFileSync('shared/config/credentials.json', 'utf8'));

        return this.content;
    }

    authorize(credentials) {
        const { client_secret, client_id, redirect_uris } = credentials.installed;
        const oAuth2Client = new google.auth.OAuth2(
            client_id, client_secret, redirect_uris[0]);

        var token = fs.readFileSync(TOKEN_PATH, 'utf-8');
        if (token == isNullOrUndefined) {
            token = getNewToken(oAuth2Client);
        }
        oAuth2Client.setCredentials(JSON.parse(token));
        return oAuth2Client;
    }

    getNewToken(oAuth2Client) {
        const authUrl = oAuth2Client.generateAuthUrl({
            access_type: 'offline',
            scope: SCOPES,
        });
        var newToken;
        console.log('Authorize this app by visiting this url:', authUrl);
        const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout,
        });
        rl.question('Enter the code from that page here: ', (code) => {
            rl.close();
            oAuth2Client.getToken(code, (err, token) => {
                if (err) return console.error('Error retrieving access token', err);
                oAuth2Client.setCredentials(token);
                // Store the token to disk for later program executions
                fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                    if (err) return console.error(err);
                    console.log('Token stored to', TOKEN_PATH);
                });
                newToken = token;
            });
        });
        return newToken;
    }

}

我尝试添加调试消息,但没有打印任何内容,也没有抛出任何错误,如果我遗漏了什么请告诉我

运行测试后的输出

> .\node_modules.bin\mocha .\test\verify.js

Tests are appearing to be passed but console.log('mail(s) found'); didnt show up in the output

您的测试在您的网络请求完成之前完成。

请参阅 mocha 文档中的这一部分。 https://mochajs.org/#asynchronous-code

您需要使用 done 回调或 return 承诺。

如果你可以使用 async/await 我发现这是最简单的,因为 async 函数总是 return 是一个承诺:https://mochajs.org/#using-async-await