测试在其他文件中用笑话

时间:2020-09-11 10:53:11

标签: javascript testing jestjs

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

app.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。

1 个答案:

答案 0 :(得分:0)

需要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的测试;)