繁体   English   中英

如何在 Jest 中模拟 class

[英]How to mock a class in Jest

我有以下 JavaScript function (课程的一部分)我想在 Jest 中测试。

    static addPost(data){
    //write post details to json
    const allPosts = this.allPosts; //Get posts from json
    const newPostID = allPosts.length +1; // make new add for post

    const newPost = { id: newPostID, ...data }; //add new add to post
    allPosts.push(newPost); //add new post to all posts

    //writing the posts with the new posts to json
    const post = JSON.stringify(allPosts, null, 2);

    fs.writeFile('./json/data.json', post, (err) => {
        if (err) throw err;
    });
    return newPost;
}

这个 function 读取和写入 JSON 文件。 有没有一种方法可以在不写入 JSON 文件的情况下测试(使用 Jest)? 我读到了 Jest mocking 但我不知道如何开始。 任何人都可以帮忙吗?

我设法找到了我的问题的解决方案。 测试代码如下。

describe('Mocking testing fs', () => {
    jest.mock('fs');
    it('Should add new post and return it', () => {

        jest.spyOn(fs, 'writeFile').mockImplementation();
        const result = Post.addPost(testData);
        expect(fs.writeFile).toHaveBeenCalled();
        expect(typeof result).toEqual('object');

        expect(result.id).toEqual(12);
        
    })
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM