如何使用Jest

时间:2019-05-16 08:14:04

标签: reactjs unit-testing navigation jestjs

我有一个React Native应用程序,我正在其中尝试使用Jest&Enzyme编写一些集成测试。我的情况如下,我有一个组件,该组件使用getParam从上一屏幕获取传递给它的导航参数-正常工作,我只是在努力使用模拟数据在其中成功获取值。我的代码如下:

在我的容器中,我在render方法中有这个:

const tickets = navigation.getParam('tickets', null);

然后在我的测试中,我有以下内容:

const createTestProps = (testProps: Object, navProps: any = {}) =>
  ({
    navigation: {
      navigate: jest.fn(),
      getParam: jest.fn(),
      ...navProps,
    },
    ...testProps,
  } as any);

let props = createTestProps(
    {},
    {
      state: {
        // Mock navigation params
        params: {
          tickets: [
            {
              cellNumber: '123456789',
              ticketId: 'xxx',
            },
            {
              cellNumber: '123456789',
              ticketId: 'xxx',
            },
          ],
        },
      },
    }
  );

const container = mount(
    <MockedProvider mocks={mocks} addTypename={false}>
      <ThemeProvider theme={theme}>
        <TicketSummaryScreen {...props} />
      </ThemeProvider>
    </MockedProvider>
  );

正如您所看到的,我试图模拟实际的导航状态,我已经对照实际组件中实际使用的状态进行了检查,并且基本上是相同的。每次运行测试时,tickets的值仍未定义。我猜想这与我模拟getParam函数的方式有关。

有人有什么想法吗?将不胜感激!

4 个答案:

答案 0 :(得分:2)

也许尝试从getParam返回模拟数据

答案 1 :(得分:0)

尝试下面的示例代码。

    const parameters = () => {
     return "your value"
    }
     .....
        navigation: {                
            getParam: parameters,
            ... navProps
        },
        ... testProps
    });

答案 2 :(得分:0)

我刚刚在我的项目中成功解决了这个问题。我唯一的优点是可以从创建的文件中导入DT[, idx := NULL] 方法。这很棒,因为只需更改此文件即可修复所有测试。我只需要将一些模拟道具合并到render所接收的组件中。 这是以前的样子:

render

/myproject/jest/index.js

修复后:

export { render } from 'react-native-testing-library'

此设置很棒!它只是为我节省了许多重构时间,并且将来可能会为我节省更多。

答案 3 :(得分:0)

尝试一下

@MyLRU
def test(a, b=1, c=2):
    print(f'a={a}, b={b}, c={c}')
    return (a,b,c)

test(1, 2, 3)  # prints and returns
test(1, 2, 3)  # only returns (i.e. using cache)
test(1, b=2, c=3)  # still prints, but this is a limitation with lru_cache as well
test(1, c=3, b=2)  # only returns (an improvement on lru_cache behaviour I think)
test(3, 4, 5)  # prints and returns
test.cache_remove(1,2,3)
test(1, 2, 3)  # prints again
test(3, 4, 5)  # only returns (so the rest of the cache wasn't cleared)
test.cache_replace('hi there', 1, 2, 3)
test(1, 2, 3)  # only returns 'hi there' (so cache was replaced)

此处const navState = { params: { tickets: 'Ticket1', password: 'test@1234' } } const navigation = { getParam: (key, val) => navState?.params[key] ?? val, } 的值将是您要传递的参数。

相关问题