Meteorjs test Meteor methods - testing

I have the following simple Meteor Method that I want to test.
It inserts a given Object into my collection
Meteor.methods({
insertHelper(profile){
HelperCollection.insert(profile);
return true;
},
}
For Testing i use "dispatch:mocha-phantomjs"
My Test so far is the following:
describe('methods', () => {
it('can delete owned task', () => {
Meteor.call('insertHelper',{a: 1});
});
});
When running my tests I get the message " Error: Method 'insertHelper' not found [404]"
So how can I access my Meteor methods from my Test suite?

As discussed in the comments, we have to include the files where the Meteor methods are defined in order to test them :
import '/path/to/method/file.js';
or with require :
require('/path/to/methos/file.js');
EDIT
Meteor advises to use import instead of using require, if you can.

Related

An updated approach to testing vuex actions

In the "Testing Actions" documentation, there is a recommendation to use inject-loader in order to mock entire module imports, and their respective dependencies, when unit testing.
For example, you can mock the ../api/shop import found inside the ./actions file with the following:
const actionsInjector = require('inject-loader!./actions')
// create the module with our mocks
const actions = actionsInjector({
'../api/shop': {
getProducts (cb) {
setTimeout(() => {
cb([ /* mocked response */ ])
}, 100)
}
}
})
Unfortunately, that package does not support Webpack 5.
Is there an updated approach, or alternative package, that is recommended?
Thanks #Estus Flask.
The clarification/mixup was that, whilst I was using vi.mock, and it's auto-mocking algorithm :
"...will mock the module itself by invoking it and mocking every
export."
i.e. it still runs the import statements. To prevent this, a factory must be provided (see documentation), e.g.:
vi.mock('module', <factory-here>)
Which then replaces the entire file import.

Testcafe data driven testing - how to drive tests with data fetched from API

I'm having trouble figuring out how to drive tests with data fetched from a request. I've read the documentation here: https://testcafe.io/documentation/402804/recipes/best-practices/create-data-driven-tests, and all examples use static json file data available at compile time.
I can't fetch the data in fixture.before hook, because it will only be available inside of the test context, but I need to access the data outside of the test context for iteration, such that the test is inside of a for loop.
I've tried this solution: https://github.com/DevExpress/testcafe/issues/1948, however this fails with testcafe ERROR No tests found in the specified source files. Ensure the sources contain the 'fixture' and 'test' directives., even when I use the flag disable-test-syntax-validation and .run({ disableTestSyntaxValidation: true }); option.
I am looking for suggestions and workarounds so that I can await some data, then run my tests. Even if Testcafe doesn't explicitly support something like this, I figure there must be some workaround... Thanks in advance.
Edit:
file-a.ts
export function tSteps(...args) {
// some setup
const testcase = args[args.length - 1];
const testCtx = test(name, async t => {
...
});
return testCtx;
}
----
file-b.ts
export const parameterizedTest = <T>(..., testcase: (scenario: T) => TestFn) => {
// some setup...
// I have also tried awaiting rows data here, which does not work
// because tests are not discoverable at compile time
...
const scenarios: T[] = rows.map(row => {
...
});
scenarios.forEach((scenario, idx) => {
return testcase(scenario).meta({
some metadata
});
});
};
----
tests.ts
fixture(...).before(async () => {
// can't get the data i need here because it needs to be available outside of the fixture context
})
parameterizedTest<MyInterface>(some params, (scenario: MyInterface) => {
return tSteps('my test',
async f => {
// some setup
// test code goes here which uses scenario.attributex, scenario.attributey, etc.
}
).meta(...);
}
);
In v1.0.0 and later, TestCafe does not validate test syntax. Please specify the TestCafe version that you use when you see the validation error.
Unfortunately, we cannot use pseudo-code to reproduce the issue you encountered. Please share some code that we could run to see the problematic behavior.
Generally speaking, TestCafe allows you to fetch data asynchronously and then spawn tests based on the received values. For instance, the following code works fine for me with TestCafe 1.18.3:
import { fixture, test } from 'testcafe';
import fetch from './node-fetch-mock';
(async () => {
const testData = await fetch();
testData
.map(n => () => {
fixture `Fixture ${n}`
.page `https://google.com`;
test(`Test ${n}`, async t => {
await t.expect(true).ok();
});
})
.map(async test => { await test(); });
})();
node-fetch-mock.js
export default async function fetch() {
return [1, 2, 3, 4, 5];
}
The only caveat is that I have to import fixture and test explicitly because I call them from callbacks.
Could you please provide us with any test code snippet that demonstrates the problem? We need to correctly understand the cause of the problem and reproduce it on our side.

Cypress reuse test cases in multiple test suites

I am new to Cypress and trying out one POC.
The application I am working on requires me to test the same component in different test suites. Is there any why in which I can avoid rewriting the same chunk of code, like using function?
export function testWelcomeBanner() {
...
welcomeBanner.should('have.text', 'welcome');
...
}
I did try some ways, like trying to call this function from it block in test suites etc. but received errors. Any help appreciated.
You can use custom commands to reuse your scripts. You can read more about custom commands from the cypress docs.
You can write your reusable functions under cypress/support/command.js
Cypress.Commands.add('welcomeBanner', (text) => {
cy.get('locator').should('have.text', 'text');
})
You can use the above command in any of your tests like
cy.welcomeBanner('Welcome Text')
Cypress recommends using functions just as you would with plain old JavaScript.
...writing Cypress tests is JavaScript, and it's often more efficient to write a function for repeatable behavior.
Source
Put reusable functions into a separate file.
utils.js:
/// <reference types="cypress" />
export function testWelcomeBanner() {
// Add more logic as needed here. You can also return
// the result of your `cy.` call.
cy.get("div.welcomeBanner")
.should("have.text", "welcome");
}
Then import those functions in your Cypress tests.
myTest.spec.js:
/// <reference types="cypress" />
import { testWelcomeBanner } from "../utils.js"; // Adjust the path for your environment
describe("testing", () => {
it("can do something", () => {
...
testWelcomeBanner();
...
});
});

Cypress JS custom commands not working in VUE CLI

I'm trying to set up a custom command to add some session storage items in a project and it doesn't seem to be firing.
The command is as follows
Cypress.Commands.add("login", () => {
window.sessionStorage.setItem("token", "tokengoeshere");
window.sessionStorage.setItem("username", "phoenix");
cy.visit("http://localhost:8080");
});
I have added the file into cypress.json
"supportFile": "tests/e2e/support/index.js",
and the index.js looks like
// Import commands.js using ES2015 syntax:
import "./commands";
When the tests fire session storage is empty
Where are you calling that custom command?
You usually create custom commands in cypress/support/commands.js file and that makes those commands available under cy.
So paste this to your cypress/support/commands.js
Cypress.Commands.add("login", () => {
window.sessionStorage.setItem("token", "tokengoeshere");
window.sessionStorage.setItem("username", "phoenix");
cy.visit("http://localhost:8080");
});
and then call it with cy.login() from any test file. Those are usually in cypress/integration folder. For example in your case a file cypress/integration/myTestsWithCustomCommand.js:
describe("My tests using custom commands", () => {
it("1st test using custom command", () => {
cy.login();
// rest of your code test
});
});

XMLHttpRequest is not defined when testing react-native app with jest

i am trying to test a apiwrapper in a react-native based app using jest (integration testing).
When i run it in the iOs simulator everything runs fine however it wont run my jest tests correctly - i always get:
ReferenceError: XMLHttpRequest is not defined
when i try to run tests using my api wrapper, eg.:
it('Login successful with correct data', () => {
let api = Api.getInstance();
return api.login("test", "testpass")
.then(result => expect(result).toEqual('login_successful'));
});
the api class i am trying to test here does use the fetch api (not vanilla xhr). I assume its something related to jest trying to mock something but have not found a way to make it work yet.
Thanks in advance.
In my case, I'm not testing the search code but only importing it somewhere in my code path, so I decided to just mock it at the global level in a setup.js file (loaded using --require at test run). The following works for me:
// needed in react-instantsearch
class XMLHttpRequest {}
global.XMLHttpRequest = XMLHttpRequest;
I had a similar problem with lokka using XMLHttpRequest. I made a mock for lokka, which my api wrapper class depends on. You could try mocking your api wrapper.
This is what my lokka mock looks like for now. I'll add more to it when I start testing error handling.
export default class {
query() {
return new Promise(resolve => {
resolve(200);
});
}
}
You might be able to mock your api wrapper with something similar:
export default class Api {
getInstance() {
\\ However you implemented getInstance
}
login(user, password) {
return new Promise(resolve => {
resolve('login_successful');
});
}
}