小编Can*_*nta的帖子

使用 Jest 在导入的模块中模拟外部用户模块

我不知道我是否在文档中遗漏了什么,但我有这种情况:

// test.js

import User from './user'

it("should load initial data", async() => {
  const users = new User()
  const user = await users.load()
})

// User.js

import Api from './api'

export default class User {
  async load() {
    const res = await Api.fetch() // prevent/mock this in testing
  }
}
Run Code Online (Sandbox Code Playgroud)

什么是玩笑,方法,以防止/嘲笑外部Api模块User.js。我不想User.js在测试中发出真实的网络请求。

除此之外,我正在寻找更通用的模拟解决方案,即。假设我正在 React Native 中进行测试,并且我想模拟NativeModules.SettingsManager.settings.AppleLocale,例如。假设Api.fetch()调用上面的行,并且不发出 HTTP 请求

javascript jestjs

3
推荐指数
1
解决办法
2142
查看次数

Redux-observable:史诗的开玩笑测试失败

我按照文档中的步骤来测试史诗.

...
store.dispatch({ type: FETCH_USER });

expect(store.getActions()).toEqual([
   { type: FETCH_USER },
   { type: FETCH_USER_FULFILLED, payload }
]);
...
Run Code Online (Sandbox Code Playgroud)

但是我失败了,因为后来接到了第二个动作.

Test failed
    Expected value to equal:
      [{"type": "FETCH_USER"}, {"type": "FETCH_USER_FULFILLED", "payload": [some]}]
    Received:
      [{"type": "FETCH_USER"}]

    Difference:

    - Expected
    + Received

    @@ -1,20 +1,5 @@
     Array [
       Object {"type": "FETCH_USER"},
       Object {"type": "FETCH_USER_FULFILLED", "payload": [some]} ] // this is what should be.
Run Code Online (Sandbox Code Playgroud)

所以我想我应该知道派遣何时完成或类似的事情.我怎么解决这个问题?

我使用了fetch()和Rx.Observable.fromPromise而不是ajax.getJSON()

这是我的史诗.

const fetchUserEpic = (action$) =>
  action$
    .ofType(FETCH_USER)
    .mergeMap(() => {
      return Rx.Observable.fromPromise(api.fetchUser())
        .map((users) => ({ …
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs redux-observable

1
推荐指数
1
解决办法
1874
查看次数

有没有办法运行设置脚本来进行玩笑测试?

我希望运行一个定义在我的玩笑测试中多次重复使用的常量和函数的脚本,有什么方法可以做到这一点吗?例如始终运行的 setup.spec.js 或在命令行中定义参数(例如 npm jest -setup 等)?

testing jestjs

1
推荐指数
1
解决办法
2174
查看次数

Vue with jest - 使用异步调用进行测试

如何让我的测试等待我的api的结果?我正在使用vue和jest来测试我的组件.

我想测试将客户端写入数据库的方法.在我的组件中,我有以下方法:

methods: {

  onSubmitClient(){

   axios.post(`urlApi`, this.dados).then(res => {

      return res;
   })

  }
}
Run Code Online (Sandbox Code Playgroud)

在我的测试中

describe('login.vue', () => {

  let wrapper

  beforeAll(()=>{

    wrapper = mount(client, {
      stubs: ['router-link'],
      store,
      data() {
          return {
              dados: {
                  name: 'tes name',
                  city: 'test city'
              },
          };
      }
    })
  })

  it('store client', () => {

    res = wrapper.vm.onSubmitLogin()
    console.log(res);

  })

})
Run Code Online (Sandbox Code Playgroud)

我的测试不等待API调用完成.我需要等待API调用才能知道测试是否有效.如何让我的测试等待API返回?

unit-testing vue.js jestjs vuejs2

1
推荐指数
1
解决办法
1956
查看次数

开玩笑/酶浅测试React无状态组件-wrapper.find()不起作用

我在测试我的React SFC时遇到问题。我想测试'PointDetailConfig'是否具有两个'DayHours'组件(可以模拟)。我不知道为什么wrapper.find()找不到'DayHours'。它与React statefull组件一起工作。收到的值表示“ DayHours”是props.children。我应该断言wrapper.props()。children吗?感谢您提供有关如何正确测试的提示。

expect(received).toHaveLength(length)

    Expected value to have length:
      2
    Received:
      {Symbol(enzyme.__root__): {Symbol(enzyme.__root__): [Circular], Symbol(enzyme.__unrendered__): <PointDetailConfig increaseCurrentDayPeriod={[]} increaseNextDayPeriod={[]} reduceCurrentDayPeriod={[]} reduceNextDayPeriod={[]} />, Symbol(enzyme.__renderer__): {"batchedUpdates": [Function batchedUpdates], "getNode": [Function getNode], "render": [Function render], "simulateEvent": [Function simulateEvent], "unmount": [Function unmount]}, Symbol(enzyme.__node__): {"instance": null, "key": undefined, "nodeType": "host", "props": {"children": [<DayHours increaseCurrentDayPeriod={[]} increaseHours={[]} increaseNextDayPeriod={[]} name="some name" reduceCurrentDayPeriod={[]} reduceHours={[]} reduceNextDayPeriod={[]} />, <DayHours increaseCurrentDayPeriod={[]} increaseHours={[]} increaseNextDayPeriod={[]} name="some name" reduceCurrentDayPeriod={[]} reduceHours={[]} reduceNextDayPeriod={[]} />]}, "ref": null, "rendered": [{"instance": null, "key": undefined, "nodeType": "function", "props": {"increaseCurrentDayPeriod": [], "increaseHours": …
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs enzyme

1
推荐指数
1
解决办法
7123
查看次数

如何像 findOne() 一样模拟猫鼬查询?

我要模拟 mongoooose 函数find()。这是我尝试过的。

1)

jest.mock("./user.model")
UserModel.findOne.mockResolvedValue(await UserModel.findOne({email: "test@gmail.com"}))
Run Code Online (Sandbox Code Playgroud)

2)

const findOne = jest.fn();
findOne.mockResolvedValue(await UserModel.findOne({email: "test@gmail.com"}))
Run Code Online (Sandbox Code Playgroud)

但两者都不起作用,解决方案是什么?我想让 UserModel 的 findOne 始终返回特定记录。

谢谢

model find mongoose jestjs

1
推荐指数
1
解决办法
5826
查看次数

Jest 异步 API 模拟

我在 stack-overflow 上搜索过这个问题,但找不到任何与我的用例类似的东西。

我有这样的容器组件。

import React, { Component } from 'react';
import PropTypes from 'prop-types';

// API
import BookingAPI from '../../../../api/BookingAPI';

class CustomerProfilePage extends Component {
  state = {
    list: [],
    totalRecords: 0,
    pageNo: 1,
  };

  componentDidMount() {
    const { pageNo } = this.state;
    this.onGetBookingList({ pageNo });
  }

  onGetBookingList = async ({ pageNo = 0 }) => {
    const { match } = this.props;
    try {
      const result = await BookingAPI.onGetBookingList({
        passengerId: match.params.customerId,
        sortProperties: ['id'],
        limitCount: 10,
        pageNo,
      });
      this.setState({ …
Run Code Online (Sandbox Code Playgroud)

mocking reactjs jestjs enzyme

0
推荐指数
1
解决办法
3458
查看次数