Я ожидаю, что функция вернет строку, но, кажется, возвращает неопределенное. это не прохождение теста Мокко - PullRequest
0 голосов
/ 17 января 2019

У меня есть файл 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");
        })
    })
})

1 Ответ

0 голосов
/ 17 января 2019

Прежде всего, ваша функция должна вернуть свое обещание:

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");
            });
        })
    })
})
...