对于测试,我使用jest和react-test-renderer。测试应该很简单,但是我很难找到合适的例子。我尝试做类似的事情(通常我将功能保存在单独的文件中):
utils.js
export const childFunction = () => 'something';
const parentFunction = () => childFunction();
export default parentFunction;
Run Code Online (Sandbox Code Playgroud)
utils.test.js
import parentFunction from './utils.js';
it('childFunction should be called', () => {
const childFunction = jest.fn();
parentFunction();
expect(childFunction).toBeCalled();
})
Run Code Online (Sandbox Code Playgroud)
片段const childFunction = jest.fn(); 绝对行不通。调用时,parentFunction的主体仅关心其自身的作用域。但是,如果我导入childFunction并执行jest.mock(childFunction),它也将不起作用,因为jest.mock需要一个字符串,一个模块的url,而不是函数本身。
上面的示例不起作用,我正在寻找替代方法。但是,在使用ShallowRenderer渲染组件后,此方法有效。而且我想通过嵌套在另一个函数中的函数来实现类似的行为。
class Component extends React.Component {
componentDidMount() {parentFunction()}
render() {...}
}
const renderer = new ShallowRenderer();
describe("testing parentFunction", () => {
renderer.render(<Component/>);
it("parentFunction should be called", () => {
expect(parentFunction).toBeCalled();
});
});
Run Code Online (Sandbox Code Playgroud) 我正在尝试用 Jest 测试我的控制器(快速中间件)。为了解释我的问题,我将提供我的代码:
import request from 'utils/request';
import logger from 'config/logger';
const get = async (req, res, next) => {
try {
const response = await request.get('entries?content_type=category');
return res.json(response.data);
} catch (error) {
logger.error(error.response.data.message);
return next(error);
}
};
module.exports = {
get,
};
Run Code Online (Sandbox Code Playgroud)
我需要测试这个get功能。为此,我需要为其提供req,res和args。next我发现这个问题,操作员谈论嘲笑明确的请求,然后说“如何使用它”,但我不知道如何使用。这是迄今为止我看到的唯一与我的问题直接相关的主题,但答案对我不起作用(我不想使用 Nock 或任何其他库来实现测试,只是开玩笑)。
那么,如何才能成功测试这个功能呢?是通过模拟还是有其他方法?
抱歉我的英语不好,提前感谢您的帮助!