我有一个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");
})
})
})
答案 0 :(得分:1)
首先,您的函数应返回其诺言:
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");
});
})
})
})