gpt4 book ai didi

javascript - 如何测试 forEach 调用 savePost 三次?

转载 作者:行者123 更新时间:2023-11-29 15:59:30 25 4
gpt4 key购买 nike

我正在学习如何用 JavaScript 编写测试,我这里有这段代码:

function handlePosts() {
var posts = [
{ id: 23, title: 'Me Gusta JS' },
{ id: 52, title: 'Ciudad Código' },
{ id: 105, title: 'Programar Ya' }
];

for (var i = 0; i < posts.length; i++) {
savePost(posts[i]);
}
}

这调用了 savePost 三次,但我想确保当我或其他人使用时,特别是 forEach 辅助方法,我的一个测试会寻找forEach 实际上调用了 savePost 三次。

我已经开发了一个测试来检查 forEach 是否存在,换句话说,它正在被使用,而不是其他一些数组辅助方法,但不确定如何测试它是否正在做它应该做的事情正在做。

describe('forEach', function() {
it('forEach method exists', () => {
expect(forEach).toBeDefined();
});

it('forEach is calling savePost three times', () => {

});
});

我渴望了解如何思考这个问题,而不仅仅是一个答案。

我想像expect(savePost.length).toEqual(3);,但我不确定。

最佳答案

The sinon framework对此可能值得考虑,因为它允许您在应用程序逻辑中创建函数 spy ,然后您可以在测试期间查询这些函数以确定是否、如何以及多久调用这些 spy 。

对于您的代码,您可以创建 savePost() 函数的 spy “ stub ”,然后使用 sinon 确定 savePost() stub 由 handlePosts() 调用。 sinon框架provides assertion methods例如 expectation.exactly(),这是您可以确定在单元测试期间调用 stub 的次数的方法。

您需要对代码进行一些调整以集成 sinon 并使所有内容协同工作。我不确定您当前在代码库中使用的约束是什么,但是将 sinon 与您的代码集成的一种方法可能如下所示:

应用程序.js

function savePost(post) {
console.log("save post", post);
}

function handlePosts() {
var posts = [
{ id: 23, title: "Me Gusta JS" },
{ id: 52, title: "Ciudad Código" },
{ id: 105, title: "Programar Ya" }
];

for (var i = 0; i < posts.length; i++) {

/* Important to ensure handlePosts() invokes savePost() via the
exported module to enable the stubbing "replacement" and subsequent
callCount() assertion to work correctly */
module.exports.savePost(posts[i]);
}
}

module.exports = {
savePost,
handlePosts
};

测试.js

const sinon = require("sinon");

/* Import the app module shown above */
const App = require("./app");

describe("forEach", function () {

var stubSavePost;

before(() => {
/* Setup the savePost stub for use in unit test before it runs. Notice
the stub is created via the App object that is basically the
module.exports object of the app.js module above */
stubSavePost = sinon.stub(App, "savePost");
});

after(() => {
/* Restore the original state of your application logic, removing
all stubs, etc after unit test complete */
sinon.restore();
});

it("forEach is calling savePost three times", () => {

/* Call handlePosts() via the exported App module object in app.js */
App.handlePosts();

/* Use callCount assertion from sinon to verify our savePost stub
was called exactly three times */
sinon.assert.callCount(stubSavePost, 3);

});
});

希望这对您有所帮助!

关于javascript - 如何测试 forEach 调用 savePost 三次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54938290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com