gpt4 book ai didi

node.js - 开 Jest mock express ?

转载 作者:搜寻专家 更新时间:2023-10-31 22:30:48 25 4
gpt4 key购买 nike

我对 JS 很陌生,但我正在努力学习。实际上,我正在尝试模拟 express 。这是我的基类(为了测试目的而缩减):

import compression from 'compression';
import express from 'express';

export default class Index{
constructor(){}

spawnServer(){
console.log(express());
let app = express();

app.use(STATIC_PATH, express.static('dist'));
app.use(STATIC_PATH, express.static('public'));
etc...
}
}

这是我试图在一个单独的测试文件中实现的测试......:

test('should invoke express once', () =>{    
index.spawnServer();
expect(mockExpressFuncs().use.mock.calls.length).toBe(3);
})

我的问题是 - 如何让测试覆盖被测类的要求 - 这甚至可能吗?我想让我的索引使用 express 的模拟版本,其中包括 express() 和 express.require。

我确实通读了文档,并尝试了类似的东西:

const mockFunction = function() {
return {
use: useFn,
listen: jest.fn()
};
};

beforeEach(() => {
jest.mock('express', () => {
return mockFunction;
})
express = require('express');
});

但这没有用——我做错了什么? :(

谢谢。

最佳答案

创建模拟应用对象并使其由 express 模块返回。

然后您可以使用 expect(app.use.mock.calls.length).toBe(3) 或更好的 expect(app.use).toHaveBeenCalledTimes(1)

const app = {
use: jest.fn(),
listen: jest.fn()
}
jest.doMock('express', () => {
return () => {
return app
}
})

test('should invoke express once', () => {
expect(app.use).toHaveBeenCalledTimes(1)
})

关于node.js - 开 Jest mock express ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619031/

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