我想问一下如何为这个函数编写单元测试。我试着用mock-fs来模拟它,并不断得到结果的undefined。对不起,我是新来JavaSCript的。
async getAllSongs(): String[] {
const songs = await readdir(this.storageDirectory);
return songs;
}发布于 2020-11-12 09:35:47
好的,看起来你的函数是一个对象/类的一部分,但是因为我不是100%的,所以我将使用一个人为的例子。
假设在我的sample.js文件中,我有一些代码,如下所示:
//sample.js
const fs = require("fs").promises;
async function getAllSongs() {
const songs = await fs.readdir(".");
return songs;
}
module.exports = { getAllSongs };要模拟fs.readdir,您可以使用jest.mock并将其替换为返回promise的函数,因为这实际上就是fs.readdir所做的。
//sample.test.js
const fs = require("fs").promises;
const { getAllSongs } = require("./sample.js");
fs.readdir = jest.fn(() => Promise.resolve(["lol.js", "lmao.js", "wow.txt"]));
test("tests stuff", async () => {
const result = await getAllSongs();
expect(result).toEqual(["lol.js", "lmao.js", "wow.txt"]);
});因为我使用jest中的假函数来清除fs.readdir,所以在执行getAllSongs时,jest将使用我的假函数而不是原来的实现。
https://stackoverflow.com/questions/64796309
复制相似问题