我期待一个 return 字符串的函数,但似乎 return 未定义。它没有通过摩卡测试

Im expecting a function to return a string but seems to return undefined. it's not passing Mocha test

我有一个 js 文件,我在其中实现了对 API 的提取调用,返回值确实是一个字符串(或者它应该是)。

我正在尝试 运行 一个测试来检查它是否正确,但它没有通过测试。你能告诉我哪里出错了吗?

这是我的 users.js 文件代码:

const fetch = require("node-fetch");

exports.retrieveFirstUserName = () => {
    let title = "";
    fetch("https://jsonplaceholder.typicode.com/todos/1")
        .then(response => response.json())
        .then(json => {
            title = json.title;
            console.log(typeof title);
        });
};

这是测试:

var assert = require("chai").assert;
var users = require("./users");

describe("fetching function tests using ASSERT interface from CHAI module: ", function () {
    describe("Check retrieveFirstUserName Function: ", function () {
        it("Check the returned value using: assert.equal(value,'value'): ", function () {
            result = users.retrieveFirstUserName();
            assert.typeOf(result, "string");
        })
    })
})

首先,你的函数应该return它的承诺:

const fetch = require("node-fetch");

exports.retrieveFirstUserName = () => {
    let title = "";
    return fetch("https://jsonplaceholder.typicode.com/todos/1")
        .then(response => response.json())
        .then(json => {
            title = json.title;
            console.log(typeof title);
            return title;
        });
};

然后,要测试它,你必须等待承诺,然后检查。

describe("fetching function tests using ASSERT interface from CHAI module: ", function () {
    describe("Check retrieveFirstUserName Function: ", function () {
        it("Check the returned value using: assert.equal(value,'value'): ", function () {
            users.retrieveFirstUserName().then(result => {
                assert.typeOf(result, "string");
            });
        })
    })
})