vue-test-utils | TypeError: s.split is not a function - vue.js

I try to run a test with vue-test-utils, including a component that has a mixin included, which has a function using split() on a string. The test looks like this:
describe('adminExample.vue Test', () => {
const wrapper = shallowMount(adminExample, {
global: {
mixins: [globalHelpers, authGatewayForElements, storeService],
plugins: [store]
}
})
it('renders component and is named properly', () => {
// check the name of the component
expect(wrapper.vm.$options.name).toMatch('adminExample')
})
})
adminExample.vue doesn't give any error, so I don't include it here, bit it uses a mixin.
The included mixin, called authGatewayForElements, has a function called decryptToken() and simply decrypt a jwt to get some info. The parameter userToken is declared within data of this mixin. The function looks like this:
decryptToken() {
let base64Split = this.userToken.split('.')[1];
let base64 = base64Split.replace(/-/g, '+').replace(/_/g, '/');
let jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
},
Running the test giving me the error TypeError: this.userToken.split is not a function . I´m new to testing with vue-test-utils and maybe or definitely missing something that needs to beincluded in the wrapper, as I expected functions like split() don't need to be included additionally.
EDIT: I get this error on multiple functions, like find(), so I'm pretty sure I just do something wrong. Thanks in advance to anybody pointing that out.

Related

how to use dynamic assertion method name?

Let's say I have this in a test:
await t.expect(Selector('input')).ok()
And I would like to have (something like) this:
let func = 'ok';
await t.expect(Selector('input'))[func]()
This is so that I can have a map from selector to function, in order to iterate
over it and check whether some elements are in the page (ok) and some not (notOk).
My above attempt does not work and returns with an interesting error:
code: 'E1035',
data: [
'SyntaxError: test.js: await is a reserved word (325:14)'
]
I believe this is because Testcafe is doing some magic under the hood.
What would be the correct syntax to make it work?
It seems that you skipped the Selector property that you want to check (e.g. exists, visible, textContent, etc.). The following test example works properly with TestCafe v1.14.2:
import { Selector } from 'testcafe';
fixture`A set of examples that illustrate how to use TestCafe API`
.page`http://devexpress.github.io/testcafe/example/`;
const developerName = Selector('#developer-name');
const submitButton = Selector('#submit-button');
test('New Test', async t => {
await t
.typeText(developerName, 'Peter Parker')
.click(submitButton);
let assertFunc = 'ok';
await t.expect(Selector('#article-header').exists)[assertFunc]();
});

Understanding then() in Cypress

I am reading through the documentation in Cypress and I think I have an idea as to what then() does. It works like promises, where a promise returns another promise, but with then(), we are returning a new subject.
If we look at the code example below, we are using then() because we are returning a new variable, which in this case is called target.
Am I understanding this correctly? If not, can someone correct me?
it.only('Marks an incomplete item complete', () => {
//we'll need a route to stub the api call that updates our item
cy.fixture('todos')
.then(todos => {
//target is a single todo, taken from the head of the array. We can use this to define our route
const target = Cypress._.head(todos)
cy.route(
"PUT",
`api/todos/${target.id}`,
//Here we are mergin original item with an object literal
Cypress._.merge(target, {isComplete: true})
)
})
.then is used to receive the results from cy.fixture('todos'). The variable target is not significant in this code.
In your code sample, the variable that is returned from cy.fixture is named todos - the spacing of the code may be throwing you off here? The .then call is attached to the cy.fixture() call
// These 2 code blocks are the same - just different spacing
cy.fixture('todos')
.then(todos => {});
cy.fixture('todos').then(todos => {});
https://docs.cypress.io/api/commands/fixture.html#Usage
cy.fixture('logo.png').then((logo) => {
// load data from logo.png
})
Using .then() allows you to use the yielded subject in a callback function and should be used when you need to manipulate some values or do some actions.
To put it simply, it is used to play around with the yield of the previous command and work around with it in that case. THEN() command is handy and helpful in debugging the yield of the previous command.
const baseURL = "https://jsonplaceholder.typicode.com";
describe("Get Call-Expect+ normal req", () => {
it("GetPostById-Expect", () => {
cy.request(baseURL + "/posts/1").as("GetPostById");
cy.get("#GetPostById").then((response) => {
//response: status
expect(response.status).to.equal(200);
expect(response.status).to.eq(200);
});
});
Refer: https://docs.cypress.io/api/commands/then#Promises

useQuery: custom names for `loading`, `error` and `data` props

Is there a way to use custom names for loading, error and data props? When I try it, I just get undefined:
const { queryLoading, queryError, queryData } = useQuery(someQuery);
This is not a big deal,just could not find anything in documentation and thought maybe there is some trick
you can do something like this:
const { data: queryData, error: queryError, loading: queryLoading } = useQuery(someQuery);

Keep "this" in bootbox callback functions

I'm trying to keep this variable in the callback:
var that = this
// type1
bootbox.confirm("This is the default confirm!", function(result){
console.log(that.whatever);
});
// type2
bootbox.confirm({
message: "This is a confirm with custom button text and color! Do you like it?",
callback: function (result) {
console.log(that.whatever);
}
});
It looks ugly, is there any better way to do it?
You can use an arrow function:
bootbox.confirm("This is the default confirm!", result => {
console.log(this.whatever);
});
You should compile this with Babel though, older browsers may not support it. If you have the callback as a variable, you can bind it before passing:
yourCb.bind(this);
bootbox.confirm("This is the default confirm!", yourCb);

jest snapshot testing: how to ignore part of the snapshot file in jest test results

Problem: ignore some part of the .snap file test results
the question here: there are some components in my test that have a random values and i don't really care about testing them. is there any way to ignore part of my X.snap file? so when i run tests in the future it won't give me test fail results.
Now you can also use property matcher for these cases.
By example to be able to use snapshot with these object :
const obj = {
id: dynamic(),
foo: 'bar',
other: 'value',
val: 1,
};
You can use :
expect(obj).toMatchSnapshot({
id: expect.any(String),
});
Jest will just check that id is a String and will process the other fields in the snapshot as usual.
Actually, you need to mock the moving parts.
As stated in jest docs:
Your tests should be deterministic. That is, running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data.
If it's something related to time, you could use
Date.now = jest.fn(() => 1482363367071);
I know it's quite old question but I know one more solution. You can modify property you want to ignore, so it will be always constant instead of random / dynamic. This is best for cases when you are using third party code and thus may not be able to control the non deterministic property generation
Example:
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Card from './Card';
import toJSON from 'enzyme-to-json';
Enzyme.configure({ adapter: new Adapter() });
describe('<Card />', () => {
it('renders <Card /> component', () => {
const card = shallow(
<Card
baseChance={1}
name={`test name`}
description={`long description`}
imageURL={'https://d2ph5fj80uercy.cloudfront.net/03/cat1425.jpg'}
id={0}
canBeIgnored={false}
isPassive={false}
/>
);
const snapshot = toJSON(card);
// for some reason snapshot.node.props.style.backgroundColor = "#cfc5f6"
// does not work, seems the prop is being set later
Object.defineProperty(snapshot.node.props.style, 'backgroundColor', { value: "#cfc5f6", writable: false });
// second expect statement is enaugh but this is the prop we care about:
expect(snapshot.node.props.style.backgroundColor).toBe("#cfc5f6");
expect(snapshot).toMatchSnapshot();
});
});
You can ignore some parts in the snapshot tests replacing the properties in the HTML. Using jest with testing-library, it would look something like this:
it('should match snapshot', async () => {
expect(removeUnstableHtmlProperties(await screen.findByTestId('main-container'))).toMatchSnapshot();
});
function removeUnstableHtmlProperties(htmlElement: HTMLElement) {
const domHTML = prettyDOM(htmlElement, Infinity);
if (!domHTML) return undefined;
return domHTML.replace(/id(.*)"(.*)"/g, '');
}
I used this to override moment's fromNow to make my snapshots deterministic:
import moment, {Moment} from "moment";
moment.fn.fromNow = jest.fn(function (this: Moment) {
const withoutSuffix = false;
return this.from(moment("2023-01-12T20:14:00"), withoutSuffix);
});