Jest Mock返回undefined而不是value



我正在使用Jest测试react组件。我试图模拟其他依赖的函数。来自dependency的函数应该返回一个数组,但是它在控制台上显示undefined。

下面的文件是tsx文件,当我点击按钮时,它应该调用依赖函数来获取框架列表。ExitAppButton.tsx:

import React, { useContext, useState } from 'react';
import { TestContext } from '../ContextProvider';
import { useDispatch } from 'react-redux';

const ExitAppButton = (props: any): JSX.Element => {
const { sdkInstance } = useContext(TestContext);
const exitAppClicked = () => {
const appList = sdkInstance.getFrames().filter((app: any) => {app.appType === "Test App"}).length}

测试文件,signoutooverlay .test.tsx:

import * as React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import SignOutOverlay from '.';
import ExitAppButton from './ExitAppButton';
import { TestContext } from '../ContextProvider';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
const api = require('@praestosf/container-sdk/src/api');
const mockStore = configureStore([]);
jest.mock('@praestosf/container-sdk/src/api');
api.getFrames.mockReturnValue([{appType:"Test App"},{appType:"Test App"},{appType:"Not Test App"}]);
describe('Test Exit app Button', () => {
const renderExitAppButton = () => {
const store = mockStore([{}]);
render(
<Provider store={store}>
<TestContext.Provider value={{ sdkInstance: api }}>
<SignOutOverlay>
<ExitAppButton/>
</SignOutOverlay>
</TestContext.Provider>
</Provider>
);
};
it('should to be clicked and logged out', () => {
renderExitAppButton();
fireEvent.click(screen.getByTestId('exit-app-button-id'));
});

这是依赖文件,api.js

const getFrames = () => {
let frames = window.sessionStorage.getItem('TestList');
frames = frames ? JSON.parse(frames) : [];
return frames
};
const API = function () { };
API.prototype = {
constructor: API,
getFrames
};
module.exports = new API();

我模拟getFrame函数返回3个对象的数组,但是当运行测试用例时,它返回undefined。下面的错误显示:

TypeError: Cannot read property 'filter' of undefined

我嘲笑这是正确的吗?

我认为这是因为api.getFrames是未定义的,而不是模拟。

试着把mock语句改成这样:

jest.mock('@praestosf/container-sdk/src/api', () => ({
getFrames: jest.fn(),
// add more functions if needed
}));

结果是,我有另一个具有相同测试名称的文件,这导致了问题。我是Jest的初学者,给像我这样的开发人员一个提示,我们应该总是使用

单独运行测试用例文件。
jest file.test.tsx 

不是一次处理所有文件:

jest

相关内容

最新更新