首页 > 解决方案 > 用 jest 在其他文件中声明的测试函数

问题描述

我有一个测试功能的问题。函数在app.js中定义,测试文件是app.test.js 怎么导入函数,以便测试?我的目标是仅对功能进行单元测试,而不对 app.js 中的所有其他内容进行单元测试

应用程序.js

const app = express()
app.use(bodyParser.json())
const data = require('../shoppinglist/data.json')
const baseUrl = '/api/v1/shoppingLists'
module.exports = {app, client, listener, getNewestId}

function getNewestId(obj){
    let idArray = []
    for(let i = 0; i < obj.length; i++) {
        idArray.push(obj[i].id)
    }
    return Math.max(...idArray)
}

app.test.js

const appPath = '../src/app'
describe('getNewestId from Valid array', () => {
    it('should return id 3', async () => {
        jest.mock(shoppingListDataPath, () => [
            {
                "id": 1,
                "name": "filled shopping list",
                "location": "lidl",
                "targetDate": "22.03.1986",
                "priority": 1,
                "isFinished": false,
                "items": [{"count":1, "name": "vodka" }, {"count":1, "name": "vodka" }
                ]
            }, {
                "id": 2,
                "name": "filled shopping list2",
                "location": "lidl2",
                "targetDate": "22.03.1986",
                "priority": 1,
                "isFinished": false,
                "items": [{"count":1, "name": "vodka" }, {"count":1, "name": "vodka" }
                ]
            }
        ])
        const {app} = require(appPath)
        app.getNewestId = jest.fn()
        expect(app.getNewestId()).toEqual(200)
    })
})

我猜这需要/导入有问题。但我只能在这里使用require。

标签: javascripttestingjestjs

解决方案


需要该getNewestId功能并像这样测试它:

const { getNewestId } = require("./app");

const testData = [
  {
    "id": 1,
    "name": "filled shopping list",
    "location": "lidl",
    "targetDate": "22.03.1986",
    "priority": 1,
    "isFinished": false,
    "items": [{"count":1, "name": "vodka" }, {"count":1, "name": "vodka" }]
  }, {
    "id": 2,
    "name": "filled shopping list2",
    "location": "lidl2",
    "targetDate": "22.03.1986",
    "priority": 1,
    "isFinished": false,
    "items": [{"count":1, "name": "vodka" }, {"count":1, "name": "vodka" }]
  }
];

describe("getNewestId from Valid array", () => {
  it("should return id 3", () => {
    expect(getNewestId(testData)).toEqual(3);
  })
});

如果您想使用单元测试,请确保您测试的函数是pure。在您熟悉了这一点之后,考虑在其他级别上测试您的应用程序,例如,编写将影响您的 API 的测试;)


推荐阅读