我有一个 js 文件,我在其中实现了对 API 的 fetch 调用,返回的值确实是一个字符串(或者应该是)。
我正在尝试运行一个测试来检查它是否正确,但它没有通过测试。你能告诉我哪里错了吗?
这是我的 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");
})
})
})
最佳答案
首先,你的函数应该返回它的 promise :
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;
});
};
然后,要测试它,您必须等待 Promise,然后进行检查。
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");
});
})
})
})
关于javascript - 我期待一个函数返回一个字符串,但似乎返回未定义。它没有通过 Mocha 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54228060/