damianof / large-scale-apps-my-vue3-project

Companion code to the book "Large Scale Apps with Vue 3 and TypeScript"
MIT License
146 stars 32 forks source link

why i need write two await key word for unit testing? #9

Open minikiller opened 3 years ago

minikiller commented 3 years ago
import { HttpRequestParamsInterface } from "@/models/http-client"
import { MutationType } from "@/models/store"
import { useItemsStore } from "@/store/items"
import axios, { AxiosRequestConfig } from "axios"
import { MockedPromiseFactory } from "../../http/MockedPromiseFactory"
import apiClient from '@/api-client'
const itemsStore = useItemsStore()
jest.mock("axios")
const mockedAxios = axios as jest.Mocked<typeof axios>

const mockParams: HttpRequestParamsInterface = {
  url: '/path/to/your/real/LIVE/api/and-point',
  requiresToken: false
}

const mockedRequestConfig = {
  headers: {}
} as AxiosRequestConfig

const mockedPromise = MockedPromiseFactory({
  url: mockParams.url,
  statusCode: 200,
  statusText: 'Success',
  requestConfig: mockedRequestConfig,
  data: [{ id: 1, name: "Post" }],
  reject: false
})

// mockedAxios.get.mockResolvedValue({ data: [{ id: 1, name: "Post" }] })
// mockedAxios.get.mockResolvedValue(mockedPromise)

// jest.mock("axios", () => ({
//   get: () => {
//     return new Promise((resolve) => {
//       resolve({ data: [{ id: 1, name: "Post" }] })
//     })
//   }
// }))

beforeEach(() => {
  console.log("before each")
  mockedAxios.get.mockResolvedValueOnce({ data: [{ id: 1, name: "Post" }] })

})
describe("authenticate", () => {

  it("test items action ", async () => {
    //   // const commit = jest.fn()
    // await Promise.all(
    const result = await await(itemsStore.action(MutationType.items.loadItems))
    // const result = await await await itemsStore.action(MutationType.items.loadItems)
    console.log(result)
    // // await itemsStore.action({ commit })
    const items = itemsStore.state.items
    // const items = itemsStore.getters("getItems")
    console.log(items)
    expect(items).toEqual([{ id: 1, name: "Post" }])

    // expect(url).toBe("/api/authenticate")
    // expect(commit).toHaveBeenCalledWith(
    //   "SET_AUTHENTICATED", true)
  })
})

I create a unit testing for items vuex action , it must have two await to get correct result. I don't know why. would you like to explain for me? thanks!

damianof commented 2 years ago

I would suggest os isolate unit tests, do not try to test everything in the same test. I am not sure I understand your code here, it seems you are trying to test the store actions. You have multiple lines commented out. I only see one line of code that executes with await here: const result = await await(itemsStore.action(MutationType.items.loadItems))

Can you explainwhere are you using await two times?