本文介绍了如何用玩笑模拟fs.readFileSync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在我的app.js中,我具有以下功能:

in my app.js I have this function:

const bodyParser = require('body-parser')
const express = require('express')
const app = express()
const cors = require('cors')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
const dataFilePath = '../shoppinglist/data.json'
const baseUrl = '/api/v1/shoppingLists'
let client
const fileSystem = require('fs')
let data



app.post(baseUrl, (req, res) => {
    const newData = req.body
    if(newData != null && !isEmpty(newData) && isRequiredFieldGiven(newData)){
        readUpdatedData()
        newData.id = getNewestId()
        data.data.push(newData)
        //updateData(data)
        console.log(data)
        res.setHeader('Content-Type', 'application/json')
        res.statusCode = 201
        res.json({"Location" : baseUrl + '/' + newData.id})
    }else{
        res.statusCode = 400
        res.send()
    }
})

function readUpdatedData(){
    let rawData = fileSystem.readFileSync(dataFilePath)
    data = JSON.parse(rawData)
}

在测试文件中,我这样做是为了测试使用其中的readUpdatedData的API调用:

in the testfile, I'm doing this to test an API post call which is using the readUpdatedData in it:

const request = require('supertest')
const shoppingListDataPath = ('../shoppinglist/data.json')
const baseUrl = '/api/v1/shoppingLists'
const appPath = '../src/app'

describe('create list entry', () => {
it('should return 201', async () => {
   let fs = require('fs')
 jest.spyOn(fs, 'readFileSync').mockReturnValueOnce(JSON.stringify({"some" : "data"}))

    let {app} = require(appPath)
        const entry = {
            "id": 1,
            "name": "filled shopping list2",
            "location": "lidl2",
            "targetDate": "22.03.1986",
            "priority": 1,
            "isFinished": false,
            "items": [{"count": 1, "name": "vodka"}, {"count": 1, "name": "vodka"}
            ]
        }
        const res = await request(app)
            .post(baseUrl)
            .send(entry)
        expect(res.statusCode).toEqual(201)
        expect(res.body).toEqual({"Location": baseUrl + 1})
    })
})

当我使用mockImplementationOnce或mockReturnValueOnce时,在调用readFileSynch时出现错误500.我已将其更改为嘲笑或/和嘲笑返回值,然后出现错误400.然后它没有调用app.post all.

When I'm using mockImplementationOnce or mockReturnValueOnce, I've get an error 500 while it's calling readFileSynch.I've changed it to mockImplementation or/and mockReturnValue, then i've got an error 400. It doesn't call then the app.post all.

我也尝试过使用jest.fn(),但结果相同.

I've also tried with jest.fn() but was the same result.

推荐答案

模拟模块需要像这样调用mock('modulename'):

Mocking modules requires calling mock('modulename') like this:

jest.mock('fs');

请参见模拟模块手动模块​​模拟

这篇关于如何用玩笑模拟fs.readFileSync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 13:09