-
Notifications
You must be signed in to change notification settings - Fork 375
/
tdd-06-generate-data.js
58 lines (47 loc) · 1.75 KB
/
tdd-06-generate-data.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import React from 'react'
import {render, fireEvent, wait} from '@testing-library/react'
import {build, fake, sequence} from 'test-data-bot'
import {Redirect as MockRedirect} from 'react-router'
import {savePost as mockSavePost} from '../api'
import {Editor} from '../post-editor-06-generate-data'
jest.mock('react-router', () => {
return {
Redirect: jest.fn(() => null),
}
})
jest.mock('../api')
afterEach(() => {
jest.clearAllMocks()
})
const postBuilder = build('Post').fields({
title: fake(f => f.lorem.words()),
content: fake(f => f.lorem.paragraphs().replace(/\r/g, '')),
tags: fake(f => [f.lorem.word(), f.lorem.word(), f.lorem.word()]),
})
const userBuilder = build('User').fields({
id: sequence(s => `user-${s}`),
})
test('renders a form with title, content, tags, and a submit button', async () => {
mockSavePost.mockResolvedValueOnce()
const fakeUser = userBuilder()
const {getByLabelText, getByText} = render(<Editor user={fakeUser} />)
const fakePost = postBuilder()
const preDate = new Date().getTime()
getByLabelText(/title/i).value = fakePost.title
getByLabelText(/content/i).value = fakePost.content
getByLabelText(/tags/i).value = fakePost.tags.join(', ')
const submitButton = getByText(/submit/i)
fireEvent.click(submitButton)
expect(submitButton).toBeDisabled()
expect(mockSavePost).toHaveBeenCalledWith({
...fakePost,
date: expect.any(String),
authorId: fakeUser.id,
})
expect(mockSavePost).toHaveBeenCalledTimes(1)
const postDate = new Date().getTime()
const date = new Date(mockSavePost.mock.calls[0][0].date).getTime()
expect(date).toBeGreaterThanOrEqual(preDate)
expect(date).toBeLessThanOrEqual(postDate)
await wait(() => expect(MockRedirect).toHaveBeenCalledWith({to: '/'}, {}))
})