gpt4 book ai didi

javascript - 使用 Jest 模拟依赖项中的依赖项?

转载 作者:行者123 更新时间:2023-11-29 22:58:38 24 4
gpt4 key购买 nike

我需要测试这个功能:

import dependency from 'dependency';

export default values => (dispatch) => {
dispatch(dependency(values));
// More code
};

我有一个测试断言 dispatch 调用了 dependency:

import functionToTest from 'function-to-test';

jest.mock('dependency', () => () => 'dependency res');

describe('functionToTest', () => {
const dispatch = jest.fn();
functionToTest({ foo: 'bar' })(dispatch);

test('test', () => {
expect(dispatch.mock.calls[0][0]).toBe('dependency res');
});
});

我需要断言 dependancy 是用 { foo: 'bar' } 调用的。我尝试命名我的依赖模拟但是当我 console.log 它是未定义的:

import functionToTest from 'function-to-test';

const dependencyMock = jest.mock('dependency', () => () => 'dependency res');

describe('functionToTest', () => {
const dispatch = jest.fn();
functionToTest({ foo: 'bar' })(dispatch);

test('test', () => {
expect(dispatch.mock.calls[0][0]).toBe('dependency res');

console.log(dependencyMock.mock.calls) // undefined
});
});

我试图创建一个新的 Jest 函数 spy 希望我可以检查它的参数,但这返回了一个错误

import functionToTest from 'function-to-test';

const spy = jest.fn(() => 'save-form-data');

const dependencyMock = jest.mock('dependency', () => spy);

describe('functionToTest', () => {
const dispatch = jest.fn();
functionToTest({ foo: 'bar' })(dispatch);

test('test', () => {
expect(dispatch.mock.calls[0][0]).toBe('dependency res');

console.log(dependencyMock.mock.calls) // undefined
});
});

The module factory of jest.mock() is not allowed to reference any out-of-scope variables.

最佳答案

你很接近!

您需要将 mock 函数移到传递给 jest.mock 的模块工厂函数中。

然后你只需要将 dependency 导入到测试中并检查它是否按预期被调用:

import functionToTest from 'function-to-test';
import dependency from 'dependency'; // <= dependency will be...

jest.mock('dependency', () =>
jest.fn(() => 'dependency res') // <= ...this mock function
);

describe('functionToTest', () => {
it('should dispatch dependency', () => {
const dispatch = jest.fn();
functionToTest({ foo: 'bar' })(dispatch);

expect(dispatch.mock.calls[0][0]).toBe('dependency res'); // Success!
expect(dependency).toHaveBeenCalledWith({ foo: 'bar' }); // Success!
});
});

请注意,默认情况下 babel-jest 提升 jest.mock 调用并且它们在测试文件中的任何其他内容之前运行,因此模块工厂函数传递给 jest .mock 必须完全独立。

关于javascript - 使用 Jest 模拟依赖项中的依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56082239/

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