gpt4 book ai didi

javascript - 从默认导入开 Jest 模拟异步函数

转载 作者:行者123 更新时间:2023-11-29 23:16:50 26 4
gpt4 key购买 nike

我正在尝试模拟一个作为默认导出导出的异步函数,但我得到的只是TypeError: Cannot read property 'then' of undefined

我要模拟的是config.js:

const configureEnvironment = async (nativeConfig) => {
return { await whatever() }
}

我正在测试的文件是 Scene.js:

import configureEnvironment from './config';

class Scene extends React.Component {
constructor(props) {
nativeConfig = {};
configureEnfironment(nativeConfig).then((config) => {
// Do stuff
}
}
}

我的测试文件是Scene.test.js:

let getScene = null;
const configureEnvironmentMock = jest.fn();

describe('Scene', () => {
jest.mock('./config', () => configureEnvironmentMock);

const Scene = require('./Scene').default;

getScene = (previousState) => {
return shallow(
<Scene prevState={previousState}>
<Fragment />
</Scene>,
);
};

it('calls configureEnvironment with the nativeConfig', async () => {
expect.assertions(1);
const nativeConfig = {};

getScene(nativeConfig);

expect(configureEnvironmentMock).toHaveBeenCalledWith(nativeConfig);
});
});

然而,运行测试的结果是:

TypeError: Cannot read property 'then' of undefined

我知道问题出在我模拟 configureEnvironment 的过程中,但我无法让它工作。

我也试过像这样模拟函数:

jest.mock('./config', () => {
return {
default: configureEnvironmentMock,
};
});

但它的结果是:

TypeError: (0 , _config2.default) is not a function

最佳答案

模拟模块默认导出的一种干净简单的方法是使用 jest.spyOn结合 mockImplementation 等功能.


这是一个基于上述代码片段的工作示例:

配置.js

const whatever = async () => 'result';

const configureEnvironment = async (nativeConfig) => await whatever();

export default configureEnvironment;

场景.js

import * as React from 'react';
import configureEnvironment from './config';

export class Scene extends React.Component {
constructor(props) {
super(props);
configureEnvironment(props.prevState).then((config) => {
// Do stuff
});
}
render() {
return null;
}
}

场景.test.js

import React, { Fragment } from 'react';
import { shallow } from 'enzyme';

import { Scene } from './Scene';
import * as config from './config';

describe('Scene', () => {

const mock = jest.spyOn(config, 'default'); // spy on the default export of config
mock.mockImplementation(() => Promise.resolve('config')); // replace the implementation

const getScene = (previousState) => {
return shallow(
<Scene prevState={previousState}>
<Fragment />
</Scene>,
);
};

it('calls configureEnvironment with the nativeConfig', async () => {
expect.assertions(1);
const nativeConfig = {};

getScene(nativeConfig);

expect(mock).lastCalledWith(nativeConfig); // SUCCESS
});
});

关于javascript - 从默认导入开 Jest 模拟异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52442024/

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