axios / moxios Goto Github PK
View Code? Open in Web Editor NEWMock axios requests for testing
License: MIT License
Mock axios requests for testing
License: MIT License
Hi,
I have some tests that require wildcards (see example below) but it doesn't look to be working as expected (the requests is not mocked).
moxios.stubRequest('/comments/.*/vote', { status: 200, response: { success: true } })
Any idea why this could be happening?
Thanks in advance
I am writing a test for a post call to my database to create a user, delete a user, and not create user for duplicate email. The issue is that moxios.requests.mostRecent() is calling the very last 'it' block even though it hasn't been called yet.
what am I missing?
Test Code:
describe("\tBackend API Works", ()=>{
let data, onFulfilled, onRejected, sandbox;
beforeEach(()=>{
data = { email: user, password: pw}
moxios.install()
onFulfilled = sinon.spy()
onRejected = sinon.spy()
})
afterEach(()=>{
data = { email: user, password: pw}
moxios.uninstall()
onFulfilled = ""
onRejected = ""
})
it("\tCreates Account (API)", function(){
this.timeout(5000);
axios.post(ROOT_URL+'/api/signup', data).then(onFulfilled).catch(onRejected)
moxios.wait(function () {
let request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
"statusMessage": "Success, User Created!",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1ODZhZWU2NTU1ZjE4YzBlYjhmNDNlNDMiLCJpYXQiOjE0ODM0MDI4NTQzMTJ9.9P4Zw-9gC7A2BHGvHWrdx3d1zmV3MGC96APsexl_n4c"
}).then(()=>{
expect(onFulfilled.getCall(0).args[0]).to.exist;
done()
})
})
})
it("\tDeleted Account (API)", function(){
data.allow = "true";
this.timeout(5000);
axios.post(ROOT_URL+'/api/a666Route', data).then(onFulfilled).catch(onRejected)
moxios.wait(function () {
let request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
"statusMessage": "Deleted User"
}).then(()=>{
expect(onFulfilled.getCall(0).args[0]).to.exist;
done()
})
})
})
it("\tWont Let You Signup w/ a Duplicate Username", function(done) {
this.timeout(5000);
axios.post(ROOT_URL+'/api/signup', {"email": "Dan", "password": "Dan"}).then(onFulfilled).catch(onRejected)
moxios.wait(function () {
let request = moxios.requests.mostRecent()
request.respondWith({
status: 422,
"statusMessage": "Email is in use."
}).then(()=>{
expect(onRejected.getCall(0)).to.exist;
done()
})
})
})
})
As an enhancement, it would be great to support mocking axios timeouts with moxios.
Timeouts are specific to the axios implementation and cannot (currently) be simulated with responses alone.
Here is a PR with a potential enhancement: #8
I am using Webpack in React (16.12)and after running test getting below error
I am testing with Jest and enzyme
Error: Uncaught [TypeError: Cannot read property 'respondWith' of undefined]
at reportException (/Users/saurabh/Desktop/project/rewards-app-fe/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:66:24)
at Timeout.callback [as _onTimeout] (/Users/saurabh/Desktop/project/rewards-app-fe/node_modules/jsdom/lib/jsdom/browser/Window.js:680:7)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) TypeError: Cannot read property 'respondWith' of undefined
at /Users/saurabh/Desktop/project/rewards-app-fe/src/Store/Actions/AuthActions/AuthActions.test.js:35:15
at Timeout.callback [as _onTimeout] (/Users/saurabh/Desktop/project/rewards-app-fe/node_modules/jsdom/lib/jsdom/browser/Window.js:678:19)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
I tried using https://www.npmjs.com/package/@types/moxios in TypeScript:
import moxios from 'moxios';
describe('MoxiosTest', () => {
beforeEach(() => {console.log(moxios); moxios.install();});
afterEach(() => moxios.uninstall());
it('test', () => {
console.log(moxios);
});
});
and getting error:
TypeError: Cannot read property 'install' of undefined
at Context.<anonymous> (webpack:///src/api/testing1.test.js:5:75 <- src/api/testing1.test.js:1926:53)
I think the problem is how moxios gets exported from moxios.js.
I had to modify:
exports.default = moxios;
module.exports = exports['default'];
to
module.exports = moxios;
module.exports.default = moxios;
in order to get the default import to work.
This is similar to how axios is exported in axios.js:
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
Hello,
I would like to test axios interceptors.
Is there a way to do this with moxios?
I currently have this interceptor:
axios.interceptors.response.use(null, (error) => {
if (error.response.status === 401) {
window.location.assign(`${error.response.data.loginUrl}/?redirect=${encodeURIComponent(window.location.href)}`);
}
return Promise.reject(error);
});
And have a test like so:
test('should redirect if 401', (done) => {
window.location.assign = jest.fn();
moxios.withMock(function () {
axios.get('/foo');
moxios.wait(async () => {
const request = moxios.requests.mostRecent();
await request.respondWith({
status: 401,
response: {
data: {
loginUrl: 'hello.world'
}
}
});
expect(window.location.assign).toHaveBeenCalled();
done();
});
});
});
This throws me: Error: Request failed with status code 401
.
And any console.log in the interceptor isn't displayed.
Any idea how I could proceed?
Thank you!
test('should fails with incorrect secret_key', (done) => {
const errorResp = {
status: 422,
response: mock_objects.auth_inv_secret
};
conf.secret_key = 'aaabbb';
let api = new ApiRequest(conf);
api.Auth(); //call to backend
moxios.wait(function () {
let request = moxios.requests.mostRecent();
request.reject(errorResp);
}).catch(error => {
console.log(error);
done();
});
});
Testing with jest i get -> TypeError: Cannot read property 'catch' of undefined
Seems there is a problem with using firefox for travis tests right now. The builds just times out.
See here for example: https://travis-ci.org/axios/moxios
So, im using a heavily extended vue-mc,
and i am trying to ensure that the responses get handled correctly to my own project specifications,
how ever, it seems that despite the fact that vue-mc uses axios. the import for this is not being mocked, as it still has the httpAdpater, instead of the mock adapter.
Vue-mc uses a Request class with a single method to use axios, so i am unsure how to get around this.
I use karma, jasmine and phantomJS with babel-polyfill. mostRecent always returns undefined even if I call axios in the test directly.
For example:
axios = require 'axios'
moxios = require 'moxios'
describe 'Test moxios', () ->
beforeEach () ->
moxios.install()
afterEach () ->
moxios.uninstall()
it 'mostRecent should return a request', () ->
axios('http://example.com').then (result) -> console.log result
moxios.wait () ->
console.log moxios.requests.mostRecent()
# undefined
I have a test as below:
import axios from 'axios';
import moxios from 'moxios';
import Vue from 'vue/dist/vue.js';
...
window.axios = axios;
describe('Component', () => {
Vue.component('component', Component);
...
...
beforeEach(function () {
// mock axios
moxios.install(window.axios);
})
afterEach(function () {
// remove mock
moxios.uninstall(window.axios)
})
...
it('does something action on click', async() => {
document.body.innerHTML = `
<div id="app">
<component :data="[{id: 1, something: 'else'}]"
></component>
</div>
`;
const component = await createVm();
var button = document.querySelector('.button.is-success');
button.click();
await Vue.nextTick(() => {});
moxios.wait(function () {
let request = moxios.requests.mostRecent()
request.respondWith({
status: 200,
response: []
}).then(function () {
expect(component.data.something).toBe('newness');
done();
})
});
});
});
async function createVm() {
const vm = new Vue({
el: '#app',
});
await Vue.nextTick(() => {});
const component = vm.$children[0];
return component;
}
The component has a method which is triggered by the button click and has this
axios.post(actionUrl, postData)
.then( (response) => {
this.data.something = 'new';
})
.catch( (error) => {
console.log('failed ' + error.status);
});
I had expected the test to fail, but it doesn't. The component works as desired (checked in a browser). Also doing a console.log()
before the axios call also shows up during the test.
However, the axios part is not working. Doing a console.log()
doesn't show anything from inside the moxios then()
call. It's clear that I am doing something wrong I suppose, just not sure what it is.
Appreciate any insights! ๐
Hi,
I'm trying to use moxios, but I find that the requests are performed as usual and moxios.requests.mostRecent() returns undefined.
It seems that moxios does not install any mock adapter.
Here's a minimal test:
import moxios from "moxios";
import axios from "axios";
describe("moxios", () => {
it("mocks axios", () => {
console.log("Adapter before: ");
console.log(axios.defaults.adapter);
moxios.install();
console.log("Adapter after installing: ");
console.log(axios.defaults.adapter);
moxios.uninstall();
console.log("Adapter after uninstalling: ");
console.log(axios.defaults.adapter);
});
});
Output:
Adapter before:
[Function: httpAdapter]
Adapter after installing:
[Function: httpAdapter]
Adapter after uninstalling:
[Function: httpAdapter]
I run the test with this command:
node_modules/.bin/mocha --compilers js:babel-core/register moxios.js
I really like moxios and I was wondering if you are planning to support HAR files?
At the moment I am always writing definitions like:
moxios.stubRequest('http://localhost:8080/resource', {
status: 200,
responseText: {value: 'Hello'}
});
It would be great if I could load a HTTP Archive which would then define the status
and responseText
(among other values).
Example:
moxios.stubRequest('./har/response.har');
There is such a functionality provided by sinon-har-server. Maybe you can make use of that!?
Well... I think the title is enough self-explanatory ๐
I've tried to follow the documentation but for some reason can't get this ti work properly. If relevant, I'm using TypeScript, React and Jest with Enzyme.
I have something like this on my app:
public componentWillMount(): void {
Axios.get("https://hostname/token")
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
And this is my simple test spec:
import * as React from "react";
import * as Moxios from "moxios";
import { shallow } from "enzyme";
import Application from "components/Application";
describe("Application", () => {
beforeEach(() => {
Moxios.install();
});
describe("#render", () => {
test("application renders correctly", () => {
Moxios.stubRequest("https://hostname/token", {
status: 200,
responseText: {}
});
expect(shallow(<Application />)).toMatchSnapshot();
});
});
afterEach(() => {
Moxios.uninstall();
});
});
I should be getting output from the console.log(response);
but I don't. I can only get this working if I remove the Moxios.uninstall()
line from afterEach
. I've also tried other variations like beforeAll
/ afterAll
but to no avail.
For now, since I can't call Moxios.uninstall()
on my tests, I've just removed beforeEach
/ afterEach
completely and I'm calling Moxios.install()
inside the first describe
. But this doesn't fell right.
What might I be doing wrong?
What am I doing wrong?
I'm using moxios in two files to mock out API requests and getting tests that seem to randomly fail.
For example:
import { expect } from 'chai'
import moxios from 'moxios'
import { SharedState, updateRenewal, mbcRequest, fetchVersions } from '../../../app/javascript/packs/sharedState.js'
const genericResponse = {
id: 1,
status: 'approved',
versions: ['underwriting', 'approved']
}
describe('SharedState', () => {
SharedState.currentRenewal = { id: 1 }
beforeAll(() => {
moxios.install()
moxios.stubRequest('/commercial_renewals/1', {
status: 200,
response: genericResponse
})
})
afterAll(() => {
moxios.uninstall()
})
describe('updateRenewal', () => {
let basic_params = {
id: 1,
status: 'approved'
}
it('updates the attributes on the SharedState updatedRenewals field', (done) => {
let attribute = basic_params['status'];
moxios.wait(() => {
updateRenewal(basic_params);
expect(SharedState.updatedRenewals[basic_params['id']]['status']).to.equal(attribute);
done();
})
});
});
...
If I run this test file, followed by another test file with a similar moxios setup, I get various errors around afterAll
and variables being undefined and I don't quite get why.
I am trying to use moxios to mock the following scenario.
axios.default.get(imageUrl, { responseType: 'stream' })
To unit test the above, I am trying to write jest with the following.
moxios.stubRequest('http://abc.com/text.jpg', {
status: 200,
response: { data: fs.createReadStream(`${__dirname}/text.png`) }
});
But the response.data. When I use response.data.pipe(somewriteablestream) it does not work.
Any help appreciated for mocking a get request returning a stream object.
The setTimeout implementation of wait() causes requests that get queued as a result of a prior axios requests to ALSO be fulfilled.
Consider the following script which gets executed.
axios.get('https://www.google.com').then(() => {
axios.get('https://www.yahoo.com')
})
Our test file looks like so:
it('calls appropriate requests', function(done){
moxios.wait(() => {
expect(moxios.requests.mostRecent().config.url).to.equal('https://www.google.com')
moxios.wait(() => {
expect(moxios.requests.mostRecent().config.url).to.equal('https://www.yahoo.com')
done()
})
})
})
But this doesn't work, since yahoo.com becomes the last request after the first wait().
We probably need two methods, one for resolving already queued requests at the time wait() is invoked, and one for waiting until all moxios requests (including ones triggered in moxios promise handlers) are finished - maybe named moxios.waitAll()?
I'm no guru of testing frameworks, but this behavior seems desirable and typical since it gives developers much more control over what requests actually get initiated, and lets them inspect the application state at every step of the process rather than only at the very end.
Hello there.
It will be cool to add method getLast, that takes reverse array of moxios.requests and returns last of found.
It is valuable as mostRecent method in cases with splitting multiple logic inside moxios.wait method.
Example:
moxios.wait(() => {
moxios
.requests
.getLast('post', '/foo')
.respondWith(fooResponse)
.then(doSomething)
moxios
.requests
.getLast('post', '/bar')
.respondWith(barResponse)
.then(doSomething)
})
I'd like to mimic something like what jest#wasCalledWith
does so I can verify that a call was requested with the correct data. Is that currently possible? The only insight we have into that at the moment is that a URL may have been updated if it contained params
that were interpolated
I'm came across a problem while i was setting up mocking for my project.
I have an axios request that that uses axios.all to make several requests at the same time. Then i thought "how the hell am i going to mock this?".
I'd need to mock about 10 requests to mock the axios.all request, and i don't think that would even work.
Is there functionality to mock an axios.all request?
Update:
I've mocked each request indiviually but is a unefficient and painful process, maybe there's a better way?
Following the example below from the README.de
file, I'm getting request.reject
equal to undefined
. The only way that I was able to mock an error on the request was by using respondWith
passing status 4xx
. Am I doing something wrong?
moxios.wait(function () {
let request = moxios.requests.mostRecent()
request.reject(errorResp)
}).catch(function (err) {
equal(err.status, errorResp.status)
equal(err.response.message, errorResp.response.message)
done()
})
})
Current moxios
is published to npm with a webpack bundled file. This means that you must always pass an axios
instance to moxios.install()
as webpack rewrites all imports and will never use the axios
install from node_modules
in a project. It would be nice to see just a babel transform of the code be published to npm.
Trying to test retry logic of a method, so I've it wired up like this:
moxios.wait(() => {
const request = moxios.requests.at(0)
request.respondWith({
status: 401
, response: mockApiError
})
const nextRequest = moxios.requests.at(1)
nextRequest.respondWith({
status: 200
, response: mockApiResponse
})
})
const mockRequest = {
headers: {}
, method: 'get'
, url: 'to/no/where'
}
const response = await tryMakeRequest(mockRequest)
expect(response.status).toBe(200)
expect(response.data).toEqual(mockApiResponse)
The test fails with this error:
Timeout - Async callback was not invoked within timeout specified by
jasmine.DEFAULT_TIMEOUT_INTERVAL.
at node_modules/jest-jasmine2/build/queue_runner.js:64:21
at Timeout.callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:523:19)
at ontimeout (timers.js:469:11)
at tryOnTimeout (timers.js:304:5)
at Timer.listOnTimeout (timers.js:264:5)
Any ideas what am I missing here?
There are some code,
let msg
it ('should send off a request when clicked', (done) => {
moxios.stubRequest( URL, {
status: 200,
response: []
})
axios.get(URL).then(res => {
console.log(res)
msg = res
})
moxios.wait(() => {
expect(msg.status).toEqual(200)
done()
})
})
When I test it, I found out,two URL as long as it is the same, the test will be successful.
It does not get the interface from the server side.
What I want to know is how to get the interface through the server๏ผ
Seems stubRequest
doesn't work inside withMock
.
If I use moxios.install()
/uninstall()
in beforeEach/afterEach stubRequest()
works good.
If I use just withMock()
without stubRequest
and then
moxios.wait(...
moxios.requests.mostRecent().respondWith(...).then(...)
...
it works good too.
But if I use it this way
describe('Test suite', function () {
it('#1', function (done) {
moxios.withMock(function () {
moxios.stubRequest('/say/hello', {
status: 200,
responseText: 'hello'
})
let onFulfilled = jasmine.createSpy('spy1')
axios.get('/say/hello').then(onFulfilled)
moxios.wait(function () {
expect(onFulfilled.calls.mostRecent().args[0].data).toBe('hello')
done()
})
})
})
})
it doesn't work.
Moxios last version (0.4.0) just stopped working with Axios 0.19.1 - released 2 days ago.
I just changed back Axios version in my project (0.19.0) and it's working fine.
Any idea why?
Individual tests are taking too long to complete, and I have to set delay to zero manualy.
Maybe it's better to set this delay to 0 by default?
I have following file with a custom axios instance:
import axios from 'axios';
import {AxiosInstance} from 'axios';
import { Loading } from 'quasar';
let axiosInstance = axios.create({
baseURL: 'http://localhost:8080/api/'
});
axiosInstance.interceptors.request.use(function (config) {
Loading.show();
return config;
});
axiosInstance.interceptors.response.use(function (response) {
Loading.hide();
return response;
}, function (error) {
Loading.hide();
return Promise.reject(error);
});
export default axiosInstance;
I consume this file in processing and in a test, but it doesn't work.
When I use the default instance, everything works as expected:
Inside a VueJs model is do:
import axiosInstance from '../../configs/axiosInstance';
...
axiosInstance.get(todos). then ....
And in the test I use moxios as follows:
import axiosInstance from '../../configs/axiosInstance';
moxios.install(axiosInstance);
moxios.stubRequest('todos', {
status: 200,
response:
[
{
'userId': 1,
'id': 1,
'title': 'delectus aut autem',
'completed': false
},
{
'userId': 1,
'id': 2,
'title': 'quis ut nam facilis et officia qui',
'completed': false
}
]
}
)
const vm = new CardTodoComponent();
vm.$mount();
expect(vm.todos.length).equal(2);
done();
As I said, when I switch both in the test and the processing to the default axios instance, the fails succeeds and get the amount of records.
What am I doing wrong?
It would be good if typescript definition file for moxios is natively distributed
The only reason why my team hasn't switched from axios-mock-adapter to this is that we can't mock a specific method with moxios. Will this be supported in the future? I can possibly submit a PR but it would be nice with some guidance. Possibly as another argument to stubRequest?
Here's the chunk of code that gives the functionality in axios-mock-adapter: https://github.com/ctimmerm/axios-mock-adapter/blob/811a6a73de6bec643d64fa619fee136a0e3e841f/src/index.js#L86
I'm trying to use stubtimeout
in version 0.3.0
but it doesn't seem to be included in the dist
files.
Am I missing something or is it not present in the build of 0.3.0
?
Hello!
I found the following example syntax not as intuitive as it could be:
// Alternatively URL can be a RegExp
moxios.stubRequest(/say.*/, {/* ... */})
Could I recommend the following?
// Alternatively URL can be a RegExp, useful when testing URLs with parameters
moxios.stubRequest( new RegExp("/say/.*"), {/*...*/})
How to mock reject reponse with status > 400 .
I want to mock errorneous response i.g.
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 422,
response: { message: 'problem' },
});
});
How can I do it?
Scenario
During development I am using stubRequest
to return mock data for api endpoints that I know are incomplete.
Problem
On urls where there is no stub request to intercept the fetch, the fetch still never goes through - almost like moxios is catching EVERYTHING that goes through axios and not just the urls that match one of the stub requests.
Question
How can I have SOME fetches (which match a stubRequest) return mock data while allowing other fetches (which don't match any stub requests) return real data?
code
moxios.install();
const stubs = {};
//todo: make top three expressions pull from constants @jkr
stubs["^navigationMock"] = navigationMock;
stubs["^ancillaryMock"] = ancillaryMock;
stubs["^pageMock"] = pageMock;
stubs[constants.EVENT_CALENDAR_HREF] = eventCalendarMock;
stubs[constants.STYLE_GUIDE_HREF] = styleGuideMock;
for (const key in stubs) {
const re = new RegExp(key);
const mock = stubs[key];
// console.log(key, re, stubs[key])
moxios.stubRequest(re, {
status: 200,
response: mock
});
}
// console.log(moxios);
axios.create();
When get() method is called with url it might return wrong result due to bug in RegExp testing.
Snippet to reproduce:
it('should find single stub by url using RegExp', function () {
moxios.stubOnce('GET', /^\/users\/\d+$/ , {
status: 200
})
let request = moxios.stubs.get('GET', '/users/12345')
notEqual(request, undefined)
})
Many stubbing libraries (SinonJS in particular) provide a handy way to stub out built in date and timers. In Sinon this is sinon.useFakeTimers()
. However, since the wait()
function internally uses setTimeout, you have to manually increment the clock in order to get the wait()
callback to fire, which is annoying.
when i use redux, and i click a button, call a action, in action, a instance of axios was called, code like this
beforeEach(() => {
moxios.install(instance);
store = configureStore(initialStore)
wrapper = Enzyme.mount(
<Provider store={store}>
<AppInput onChange={updateAppInfo}/>
</Provider>
)
})
it('updateAppInfo', (done) => {
moxios.stubRequest('/app/get', {
status: 200,
responseText: 'hello'
})
wrapper.find('.xj-appinput-item').at(0).simulate('click');
moxios.wait(() => {
let request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: { a: 22 }
}).then(() => {
});
});
})
updateAppInfo function send a request which url is /app/get
,
and as expect, moxios will catch this request,
but i got this error,
TypeError: Cannot read property 'respondWith' of undefined
so i wonder how to fix this?
Hi, I added an unit testing using moxios for our React application.
It seems that my test with moxios passes even though the test is a false condition.
Here is the code.
login-test.js
` . import React from 'react';
import Login from '../../src/components/Login';
import axios from 'axios';
import moxios from 'moxios';
describe('Login test', function () {
let data;
beforeEach(function () {
data = { email: 'sample', password: 'sample' }
moxios.install();
});
afterEach(function () {
data = { email: 'sample', password: 'sample' }
moxios.uninstall();
});
it('Send Login data', function (done) {
axios.post('/login');
moxios.wait(function () {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: { message: 'successfull', status: '200' },
}).then(function () {
equal(login.called, true)
})
});
done()
})
})`
// test passed
Here is the code with a false condition. I didn't assign a post router.
` . import React from 'react';
import Login from '../../src/components/Login';
import axios from 'axios';
import moxios from 'moxios';
describe('Login test', function () {
let data;
beforeEach(function () {
data = { email: 'sample', password: 'sample' }
moxios.install();
});
afterEach(function () {
data = { email: 'sample', password: 'sample' }
moxios.uninstall();
});
it('Send Login data', function (done) {
**axios.post('/');**
moxios.wait(function () {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: { message: 'successfull', status: '200' },
}).then(function () {
equal(login.called, true)
})
});
done()
})
})`
This test passed. I tried testings with several conditions and the tests passed in most cases.
Hey,
I'm using this mock library and I see that the needed changes for my case in this merged PR -> #35
Can I get some estimation on when this change will be landed? (Last release was 3 years ago on npm)
Without this PR you can't mock multiple requests with the same URL if the method is the only difference between them.
Thanks
How can i achieve the following case:
I want moxios adapter to be set only in particular url patterns.
Other url patterns should have axios default adapter.
I was able to change moxios adapter either for all urls used by axios or none of them.
Can this be achieved or is it a bad practice?
The docs for stubOnce
state: "Stub a response to be used one or more times to respond to a request matching a method and a URL or RegExp.".
From the method name I was expected a different behavior, namely that the response would only used once and subsequent requests would fail.
This example seems wrong
moxios.wait(function () {
let request = moxios.requests.mostRecent()
request.reject(errorResp)
}).catch(function (err) {
equal(err.status, errorResp.status)
equal(err.response.message, errorResp.response.message)
done()
})
})
wait()
doesn't return Promise so we can't chain catch()
For context, I'm using TypeScript, React and Jest with Enzyme.
On my application I'm doing something like this:
import * as React from "react";
import Axios from "axios";
export default class Application extends React.Component<any, any> {
public constructor() {
super();
Axios.defaults.baseURL = "https://hostname.herokuapp.com";
}
public componentWillMount(): void {
Axios.get("/token")
.then((response) => {
console.log(response);
});
}
}
And I'm trying to stub the /token
request like this:
import * as React from "react";
import * as Moxios from "moxios";
import { shallow } from "enzyme";
import Application from "components/Application";
describe("Application", () => {
Moxios.install();
test("something", () => {
shallow(<Application />);
Moxios.stubRequest("/token", {
status: 200,
response: {
message: "Hello Axios"
}
});
});
});
The console.log(response);
should output my mocked response, but it's not. However, if I change the stubRequest
call to:
Moxios.stubRequest("https://hostname.herokuapp.com/token", ...);
It works... But that kinda defeats the purpose of the baseURL
property. Well, it works on the code so that's not too bad, but why is it not working on testing too?
I've tried I've also tried this:
Moxios.install(Axios.create({
baseURL: "https://hostname.herokuapp.com"
}));
But it didn't work...
What am I missing?
Hi, I'm using Moxios to build a live demo of SPA project and while was able to do so, its not really strightforward.
I would like to request a function similar to stubRequest with a callback.
moxios.stubRequest('/say/hello', request => {
const data = {} // do your thing
return {
status: 200,
data
}
})
I'm trying to run an example using Jest that's nearly identical to the first example in the docs, and I'm getting the following error after I try to run expect(A).toEqual(B)
:
(0 , _jest2.default) is not a function
I'm only getting Network Error
from all responses
instance = axios.create({ baseUrl: 'example.com' })
I have a test with moxios and those results are an error, I read the docs and I wrote the same form that of these describe in how define an async test,the error is, I read also the docs of jasmine. Do you knows what happens?
Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
at node_modules/jest-jasmine2/build/queue_runner.js:65:21
at Timeout.callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:523:19)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)
Test
`import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import multi from 'redux-multi';
import promise from 'redux-promise';
import moxios from 'moxios';
import LocalStorageMock from '../../layouts/mock-localstorage'
import { password, leavePassword, restorePass, types } from '../../actions/password-actions';
//const middlewares = [multi];
const middlewares = [multi,thunk];
//const middlewares = [multi,promise];
const mockStore=configureStore(middlewares);
const baseUrl = 'localhost/project';
const REGISTER_ENDPOINT = 'account/password';
const RESTORE_ENDPOINT = 'account/reset_password/init';
let originalTimeout;
beforeEach(() =>{
//originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;//that not works
//jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000;//that not works
moxios.install();
});
afterEach(() => {
localStorage.clear();
moxios.uninstall();
//jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;//that not works
});
global.localStorage= new LocalStorageMock('auth');
it('when user set password isnt valid', async(done)=>{ //it('when user set password isn
t valid',()=>{
const store = mockStore({password:{}});
const path = baseUrl + REGISTER_ENDPOINT;
moxios.stubRequest(path,{
status: 404,
response:{
message:'BAD_REQUEST'
}
});
const values = {
newPassword: 'password',
email: '[email protected]',
key: 'eXyGsaerFAS213das&%ASDas'
};
store.dispatch(password(values));
const actions= store.getActions();
expect(actions.length).toBe(2);
expect(actions[0].type).toBe(types.SETPASS_STARTED);
expect(actions[1].type).toBe(types.SETED_PASS);
expect(actions[1].payload).not.toBe(null || undefined);
await actions[1].payload.then((response)=>{
expect(actions[1].payload.response.status).toEqual(404);
expect(actions[1].payload.message).toEqual('BAD_REQUEST');
done();
});
});Action creator
// tipos de acciones que se generaran
export const types = {
SETPASS_STARTED: '#password/setPass_started',
SETED_PASS: '#password/seted_pass',
LEAVE_COMPONENT: '#password/leave_pass',
RESTORE_STARTED: '#password/restore_started',
RESTORE_PASS: '#password/restore',
};
// creador de accion cuando se setea el password por primera vez
export const password = (values) => {
const data = {
newPassword: values.password,
email: values.email,
key: values.key,
};
let request = axios.post(${Config.baseUrl}${REGISTER_ENDPOINT}
, data, {
auth: {
username: Config.oauth.appUser,
password: Config.oauth.appPassword,
},
});
return [{
type: types.SETPASS_STARTED,
}, {
type: types.SETED_PASS,
payload: request,
}];
};`
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.