Showing posts with label JEST. Show all posts
Showing posts with label JEST. Show all posts

Monday, July 4, 2022

How to fix " ReferenceError: document is not defined" in Jest?

When I setup a test again the AppShell in Micro-Frontend Application Development, then I added the test command to the scripts section in the package.json 

   "test": "jest"

now the scripts section should be shown as below.

 "scripts": {
    "dev": "tsc --watch --outDir dist",
    "build": "tsc --outDir dist",
    "lint": "eslint *.ts*",
    "storybook": "start-storybook",
    "test": "jest"
  },


However when i run the test with pnpm test, I encoutered the error in the following image.







"AppShell › renders

    The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.

    Consider using the "jsdom" test environment."


based on the suggestion, i added the environment tag jsdom to the test command, then the test run is succeed.

"scripts": {
    "dev": "tsc --watch --outDir dist",
    "build": "tsc --outDir dist",
    "lint": "eslint *.ts*",
    "storybook": "start-storybook",
    "test": "jest --env=jsdom"
  },

The successful test run is shown below.





Monday, February 1, 2021

how to fix " ReferenceError: fetch is not defined" in redux testing with nock and jest?

when i implemented a test a case against the API call to test the reducer, we can use NOCK to mock the API with JEST test run.

here is the sample code for the above test case.

import { createStoreapplyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import nock from 'nock'

import { fetchUser } from '../../src/actions'
import usersReducer from '../../src/reducers/users'

// global.fetch = require('node-fetch');
const middlewares = [ thunk ]
let store

beforeEach(() => {
  store = createStore(usersReducerapplyMiddleware(thunk))
})

afterEach(() => {
  nock.cleanAll()
})

test('initial state should be empty array (no users)', () => {
  expect(store.getState()).toEqual([])
})

test('fetchUser action should add user object to state', () => {
  const username = 'dan'
  const realname = 'Dan Deng'
  const userObj = { username:usernamerealname:realname }
  console.log(userObj)
  nock('http://localhost:8080/')
    .get(`/api/users/${username}`)
    .reply(200userObj)

  expect.assertions(1)

  const action = fetchUser(username)
  return store.dispatch(action)
    .then(() =>
      expect(store.getState()).toContainEqual(userObj)
    )
})


however i ran the test case with JEST, the following error came immediately. since i use fetch function from fetch-node module.

 ● fetchUser action should add user object to state

    ReferenceError: fetch is not defined

      23 |     types:[FETCH_USER_REQUEST, FETCH_USER_SUCCESS, FETCH_USER_FAILURE],
      24 |     promise: fetch(`http://localhost:8080/api/users/${username}`)
    > 25 |     .then(response=>response.json())
         |      ^
      26 | })
      27 |
      28 | export const createUser=(username, realname, password)=>thunkCreator({

      at fetchUser (src/actions/users.js:25:6)
      at Object.<anonymous> (_test_/reducers/users.test.js:88:18)

  ● fetchUser action should add user object to state

    expect.assertions(1)

    Expected one assertion to be called but received zero assertion calls.

      84 |     .reply(200, userObj)
      85 |
    > 86 |   expect.assertions(1)
         |          ^
      87 |
      88 |   const action = fetchUser(username)
      89 |   return store.dispatch(action)

      at Object.<anonymous> (_test_/reducers/users.test.js:86:10)


the fix is very easy, we just have to add the reference to fetch in the test file. the test case was passed and succeed.

 global.fetch = require('node-fetch');


Sunday, January 31, 2021

how to use test object array contain element which match giving object?

 when we write a test case to verify that an object array contains specific object within JEST framework

we can use the following code to handle it .

let posts=[]

beforeAll(()=>{
    posts.push({title:'test'user:'dan'})
    posts.push({title:'hello world'user:'dan'})
})

test('test post exists',()=>{
    expect(posts).toEqual(
        expect.arrayContaining([
            expect.objectContaining({title: 'test'})
        ])
    )
})