Я пытаюсь проверить вывод console.log в моих тестах ...
Это нормально в первом тесте, но не во втором ... Я думаю, это должно быть проблемой с фиктивной функцией ... это должно быть сброшено?
Я пытался использовать
jest.resetAllMocks()
но возникает ошибка ..
вот мой тестовый код:
import Blog from '../../src/client/js/blog.js';
import mockAxios from "axios";
jest.mock('axios');
describe('client/blog', () => {
beforeEach(() => {
console.log = jest.fn();
});
afterEach(() => {
mockAxios.delete.mockClear();
console.log.mockClear();
});
it('set the DeletePostHandler', async function () {
// WHEN
...
jest.spyOn(window.location, 'assign').mockImplementation(url => console.log('resolved'))
// WHEN
await document.querySelector('#link_1').click();
// THEN
expect(mockAxios.delete).toHaveBeenCalledTimes(1);
expect(console.log.mock.calls[0][0]).toBe('resolved')
});
it('does not set the DeletePostHandler', async function () {
// WHEN
...
jest.spyOn(window.location, 'assign').mockImplementation(url => console.log('rejected'))
// WHEN
await document.querySelector('#link_1').click();
// THEN
expect(mockAxios.delete).toHaveBeenCalledTimes(1);
expect(console.log.mock.calls[0][0]).toBe('rejected')
});
});
спасибо за отзыв
ОБНОВЛЕНИЕ 1
когда я не высмеиваю консоль, я могу проверить правильный вывод:
PASS tests/client/blog.spec.js
client/blog
✓ set the DeletePostHandler (28ms)
✓ does not set the DeletePostHandler (4ms)
console.log tests/client/blog.spec.js:26
resolved
console.log tests/client/blog.spec.js:43
rejected
PASS tests/client/comment.spec.js
client/comment
✓ test setup OK (2ms)
Test Suites: 2 passed, 2 total
ОБНОВЛЕНИЕ 2
Как рекомендовано в комментарии @Yuri, я отказался от проверки console.log, обновил спецификации и добавил несколько console.log для проверки выходных данных. Я все еще не могу правильно проверить второй тест ... как window.location .assign mock не сбрасывается правильно для второго теста ....
/ тесты / клиент / blog.spec.js
import Blog from '../../src/client/js/blog.js';
import mockAxios from "axios";
jest.mock('axios');
describe('client/blog', () => {
beforeAll(() => {
jest.spyOn(window.location, 'assign').mockImplementation(() => {});
});
afterEach(() => {
mockAxios.delete.mockClear();
});
afterAll(() => {
// clean up after all tests
window.location.assign.mockRestore()
});
it('set the DeletePostHandler', async function () {
// WHEN
const post = '<div class="posts"><div class="post">' +
'<p>Today should be a great day to be alive!</p>' +
'<div class="is-hidden">' +
'<a id="link_1" class="delete-post" href="/admin/edit-post/1" data-post-id="1">delete<i class="is-hidden"></i></a>' +
'</div></div>';
document.body.innerHTML = post;
Blog.pageReady('admin-index');
// WHEN
await document.querySelector('#link_1').click();
// THEN
expect(mockAxios.delete).toHaveBeenCalledTimes(1);
expect(window.location.assign).toBeCalledWith('/admin?cache=false');
});
it('does not set the DeletePostHandler', async function () {
// WHEN
const post = '<div class="posts"><div class="post">' +
'<p>Today should be a great day to be alive!</p>' +
'<div class="is-hidden">' +
'<a id="link_1" class="delete-post" href="/admin/edit-post/" data-post-id="">delete<i class="is-hidden"></i></a>' +
'</div></div>';
document.body.innerHTML = post;
Blog.pageReady('admin-index');
// WHEN
await document.querySelector('#link_1').click();
// THEN
expect(mockAxios.delete).toHaveBeenCalledTimes(1);
expect(window.location.assign).toBeCalledWith('/admin?cache=true');
});
насмехается / axios.j S
export default {
delete: jest.fn((url) => {
if (url === '/api/v1/blog/1') {
return Promise.resolve({
data: {},
status: 200,
statusText: 'OK',
headers: {}
});
} else {
return Promise.reject({
data: {},
status: 400,
statusText: 'Error',
headers: {}
});
}
})
};
/ client / blog.js
const deletePost = id => {
axios.delete(`${API_BASE}/blog/${id}`, {
headers: { 'Content-type': 'application/json' },
data: null, // data null is necessary to pass the headers
})
.then((result) => {
console.log('AXIOS RESOLVED: ', result);
console.log('GOING TO CALL window.location.assign with /admin?cache=false');
window.location.assign('/admin?cache=false');
})
.catch((e) => {
console.log('AXIOS REJECTED: ', e);
console.log('GOING TO CALL window.location.assign with /admin?cache=true');
window.location.assign('/admin?cache=true');
});
};
Консоль
console.log src/client/js/blog.js:12
AXIOS RESOLVED: { data: {}, status: 200, statusText: 'OK', headers: {} }
console.log src/client/js/blog.js:13
GOING TO CALL window.location.assign with /admin?cache=false
console.log src/client/js/blog.js:17
AXIOS REJECTED: { data: {}, status: 400, statusText: 'Error', headers: {} }
console.log src/client/js/blog.js:18
GOING TO CALL window.location.assign with /admin?cache=true
PASS tests/client/comment.spec.js
● client/blog › does not set the DeletePostHandler
expect(jest.fn()).toBeCalledWith(expected)
Expected mock function to have been called with:
"/admin?cache=true"
as argument 1, but it was called with
"/admin?cache=false".
50 | // THEN
51 | expect(mockAxios.delete).toHaveBeenCalledTimes(1);
> 52 | expect(window.location.assign).toBeCalledWith('/admin?cache=true');
| ^
53 | });
54 |
55 | });
at Object.toBeCalledWith (tests/client/blog.spec.js:52:36)
at tryCatch (node_modules/regenerator-runtime/runtime.js:62:40)
at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:296:22)
at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:114:21)
at step (tests/client/blog.spec.js:22:191)
at tests/client/blog.spec.js:22:361